0

I need to print a string as part of a list that has 3 backslashes in it in Python. However, this is not appearing to be as simple as I expected.

print ["\\\"]

Traceback (most recent call last):
  File "<string>", line 1, in <fragment> 
EOL while scanning string literal: <string>, line 1, pos 13

Any string that has an odd number of backslashes will do this because Python is escaping the quote. So I tried escaping myself:

print ["\\\\\\"]
['\\\\\\']

which is 6 backslashes. Not what I wanted. This has stumped a few of us around the water cooler.

Randy
  • 908
  • 12
  • 30
  • 1
    Your second example is correct, but you are seeing the `repr` of the string within the list that you're printing. Try `print "\\\\\\"`. – g.d.d.c May 29 '14 at 17:00
  • This is a python FAQ for those who want some more background. https://docs.python.org/2/faq/design.html#why-can-t-raw-strings-r-strings-end-with-a-backslash – Randy May 29 '14 at 17:08
  • I realize that now g.d.d.c. Looks like my eyes (i.e. my python interactive shell) were deceiving me. `print [len(x) for x in ["\\\\\\”]] [3]` – Randy May 29 '14 at 18:57

2 Answers2

5

'\\\\\\' is a string contain 3 backslashes. You can see that there are 3 characters in the string by applying list to it:

In [166]: list('\\\\\\')
Out[166]: ['\\', '\\', '\\']

'\\'*3 would also work:

In [167]: list('\\'*3)
Out[167]: ['\\', '\\', '\\']

Or since

In [169]: hex(ord('\\'))
Out[169]: '0x5c'

you could avoid the need to escape the backslash by using \x5c:

In [170]: print('\x5c\x5c\x5c')
\\\
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
2
print r"\\\ "

would work I think (r indicates a literal string)

(as pointed out in the comments you cant end with a backslash in raw strings ...(so I added a space))

If you didnt want the space you could

print r"\\\ ".strip()
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179