3

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.stack.imgur.com/6KGUn.png

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

Surreal Dreams
  • 26,055
  • 3
  • 46
  • 61
abasar
  • 135
  • 1
  • 2
  • 8
  • 1
    Notice in the first line of your dictionary, you have an error at the end of the line? It's because the `\` character is escaping the `'` that follows it. – Surreal Dreams Mar 20 '14 at 15:13

2 Answers2

13

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'\-/'
\-/
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 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 '/-\\'. – abasar Mar 20 '14 at 15:33
  • @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 Mar 20 '14 at 15:34
  • @user3422569: Compare `print A` with `print repr(A)` and see if there really are one or two backslashes. – Martijn Pieters Mar 20 '14 at 15:35
7

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.

Paulo Bu
  • 29,294
  • 6
  • 74
  • 73