Iam writing a code that I need to print \
character. I searched a lot and I saw this solution that to put "\\"
in a string but the problem is that when printing it will print \\
not \
and the same for |
character.
Anyone know what to do?
I've tried and searched a lot but I didn't find how to print \
not \\
or .
CodePudding user response:
\
in a string starts an escape sequence which allows using special characters. To use a plain backslash, you need to escape it; in other words, double it up: "\\"
. This works. When you print the string, it prints a single backslash:
>>> print("\\")
\
You probably tried printing it by entering the value directly on the Python terminal without calling the print
function. This will show you a representation of the Python value, including quotes and, yes, escape sequences:
>>> "\\"
"\\"
Note the quotation marks!
An alternative to the above in Python is to use raw string literals. This works everywhere except just before a quotation mark:
>>> print(r"\x")
\x
>>> print("r\")
Syntax error
By contrast, the pipe character (|
) is not special. If you want to use it, just put it directly into the string:
>>> print("|")
|
CodePudding user response:
print("\\")
Try it.