Can '\' be in a Python string?

25,155

Solution 1

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

Solution 2

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.

Share:
25,155
abasar
Author by

abasar

Updated on March 21, 2020

Comments

  • abasar
    abasar over 4 years

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

    http://i.stack.imgur.com/6KGUn.png

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

  • abasar
    abasar over 10 years
    When I write '/-\\' at the console it does show as '/-\', but when I run the program and tell it to print the 'A' list it show '/-\\'.
  • Martijn Pieters
    Martijn Pieters over 10 years
    @user3422569: don't confuse the representation with the contents. If you don't use print, just echo the value in the interpreter, repr() is called and the value is shown as a Python string literal, escaped for copying and pasting.
  • Martijn Pieters
    Martijn Pieters over 10 years
    @user3422569: Compare print A with print repr(A) and see if there really are one or two backslashes.