Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find backslash (\) in a string --Python

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.

like image 757
Ignacio Gómez Avatar asked Jul 04 '12 15:07

Ignacio Gómez


People also ask

How do you find the backslash of a string in Python?

Use the in operator to check if a string contains a backslash, e.g. if '\\' in my_str: . Backslash characters have a special meaning in Python, so they have to be escaped with a second backslash. Copied! The backslash \ character has a special meaning in Python - it is used as an escape character (e.g. \n or \t ).

How do you show backslash in string?

If you want to include a backslash character itself, you need two backslashes or use the @ verbatim string: var s = "\\Tasks"; // or var s = @"\Tasks"; Read the MSDN documentation/C# Specification which discusses the characters that are escaped using the backslash character and the use of the verbatim string literal.


4 Answers

You need to escape the backslash.

s = "\\"
like image 192
Ignacio Vazquez-Abrams Avatar answered Oct 22 '22 05:10

Ignacio Vazquez-Abrams


>>>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/

like image 27
Kurt Schroeder Avatar answered Oct 22 '22 05:10

Kurt Schroeder


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.

like image 3
Kendrick Ledet Avatar answered Oct 22 '22 07:10

Kendrick Ledet


"\\" in mystring

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

like image 2
vossad01 Avatar answered Oct 22 '22 05:10

vossad01