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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
A backslash needs to be escaped with another backslash.
print('\')
Method 3
A hacky way of printing a backslash that doesn’t involve escaping is to pass its character code to chr:
>>> print(chr(92))
Method 4
You should escape it with another backslash :
print('\')
Method 5
print(fr"{''}")
or how about this
print(r" "[0])
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0