Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can '\' be in a Python string? [duplicate]

I program in Python in PyCharm and whenever I write '\' as a string it says that the following statements do nothing. For example:

https://i.sstatic.net/6KGUn.png

Is there a way to fix this and make it work? Thanks.

like image 697
abasar Avatar asked Aug 25 '26 20:08

abasar


2 Answers

You need to double the backslash:

'/-\\'

as a single backslash has special meaning in a Python string as the start of an escape sequence. A double \\ results in the string containing a single backslash:

>>> print '/-\\'
/-\

If the backslash is not the last character in the string, you could use a r'' raw string as well:

>>> print r'\-/'
\-/
like image 65
Martijn Pieters Avatar answered Aug 27 '26 08:08

Martijn Pieters


You need to scape them to be in the string, for example:

>>>s='\\'
>>>print s
\

You can also use the r (raw string) modifier in front of the string to include them easily but they can't end with an odd number of backslash. You can read more about string literals on the docs.

like image 34
Paulo Bu Avatar answered Aug 27 '26 08:08

Paulo Bu