6
votes

How can I compare if a backslash is in my string?

I don't know how to write the backslash symbol to compare it. I try this but don't work:

Code:

s = r"\""
print s

Output: \"

If I try s = "\"" it gives " as output

I don't know how to acheive that.

Thanks for any help.

4

4 Answers

21
votes

You need to escape the backslash.

s = "\\"
6
votes
>>>mystring = "can python find this backslash \n"
>>>"\\" in r"%r" % mystring
True

while trying to filter the backslash \ character from being used in Windows filenames I searched a lot of places for answers. this is the solution worked for me. based on information I read at... http://pythonconquerstheuniverse.wordpress.com/2008/06/04/gotcha-%E2%80%94-backslashes-in-windows-filenames/

3
votes

Backslashes are used for escaping, so to display a backslash in a string literal you need to escape the backslash with another backslash.

print "\\"

prints a string with 1 backslash.

2
votes
"\\" in mystring

Where mystring is your string. Will tell you if it contains a backslash