What if I want a backslash in my string?

When I did this exercise I wondered how I would print a backslash if backslash was the escape character. As it turns out, you just put another backslash next to it!

yields:

Testing if I can print a \

Great exploration to resolve your own question. This is being saved for anyone else who wonders the same thing!

3 Likes

Another thing you can do is put r (for raw) in front of the string like so:

print (r"Testing if I can print a \\")

That will print Testing if I can print a \\.

There is one little thing with r though, backslash is still an escape for quotes, so you can’t end your string with a single backslash like so:

print(r"Testing if I can print \") // End if line error

You would need to put a space, full stop or something else to sperate the backslash and quote. You could double backslash but it will then print a double backslash though.

12 Likes

Pretty cool! Thanks for sharing.

1 Like