如何打印单个反斜杠?

当我编写 print('\')print("\")print("'\'")时,Python 不会打印反斜杠 \符号。相反,它错误的前两个和打印 ''的第三个。我应该怎样打印反斜杠?


这个问题是关于产生一个只有一个反斜杠的字符串。这是特别棘手的,因为它不能用原始字符串完成。有关为什么这样一个字符串用两个反斜杠表示的相关问题,请参阅 为什么反斜杠出现两次?。有关在其他字符串中包含文字反斜杠的信息,请参见 在 python 中使用反斜杠(不要转义)

291920 次浏览

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.

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

>>> print(chr(92))
\
print(fr"\{''}")

or how about this

print(r"\ "[0])

For completeness: A backslash can also be escaped as a hex sequence: "\x5c"; or a short Unicode sequence: "\u005c"; or a long Unicode sequence: "\U0000005c". All of these will produce a string with a single backslash, which Python will happily report back to you in its canonical representation - '\\'.