10

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.

Ignacio Gómez
  • 1,587
  • 4
  • 23
  • 41

4 Answers4

24

You need to escape the backslash.

s = "\\"
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
9
>>>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/

Kurt Schroeder
  • 106
  • 2
  • 5
3

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.

Kendrick Ledet
  • 673
  • 6
  • 9
2
"\\" in mystring

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

vossad01
  • 11,552
  • 8
  • 56
  • 109