How to print a single backslash?

PythonEscapingBackslash

Python Problem Overview


When I write print('\') or print("\") or print("'\'"), Python doesn't print the backslash \ symbol. Instead it errors for the first two and prints '' for the second. What should I do to print a backslash?

Python Solutions


Solution 1 - Python

You need to escape your backslash by preceding it with, yes, another backslash:

print("\\")

And for versions prior to Python 3:

print "\\"

The \ character is called an escape character, which interprets the character following it differently. For example, n by itself is simply a letter, but when you precede it with a backslash, it becomes \n, which is the newline character.

As you can probably guess, \ also needs to be escaped so it doesn't function like an escape character. You have to... escape the escape, essentially.

See the Python 3 documentation for string literals.

Solution 2 - Python

A backslash needs to be escaped with another backslash.

print('\\')

Solution 3 - Python

A hacky way of printing a backslash that doesn't involve escaping is to pass its character code to chr:

>>> print(chr(92))
\

Solution 4 - Python

You should escape it with another backslash \:

print('\\')

Solution 5 - Python

print(fr"\{''}")

or how about this

print(r"\ "[0])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichaelView Question on Stackoverflow
Solution 1 - PythonBucketView Answer on Stackoverflow
Solution 2 - PythonAndyView Answer on Stackoverflow
Solution 3 - PythonJean-François FabreView Answer on Stackoverflow
Solution 4 - PythonlellomanView Answer on Stackoverflow
Solution 5 - PythonTae Soo KimView Answer on Stackoverflow