如何用Python打印反斜杠?

时间:2013-09-30 13:42:01

标签: python python-2.7

当我写:

print '\'print "\"print "'\'"

Python不会打印反斜杠\符号。

我该怎么做才能获得预期的结果?

9 个答案:

答案 0 :(得分:71)

你需要通过在前面加上反斜杠来逃避你的反斜杠,是的,另一个反斜杠:

print "\\"

\字符称为转义字符,它以不同的方式解释跟随它的字符。例如,n本身只是一个字母,但当您在其前面加上反斜杠时,它变为\n,即newline字符。

正如您可能猜到的那样,\也需要进行转义,因此它不像转义字符那样起作用。你必须......逃避逃跑,基本上。

答案 1 :(得分:35)

另一个线索,如果你想要完成比打印反弹更复杂的事情,你可以将字符串声明为raw(前面有r并且它会打印出来它的所有字符都是:

>>> s = r'\abc\def'
>>> print s
'\abc\def'

这对正则表达式很有用。您可以找到more information in the docs

答案 2 :(得分:7)

需要使用另一个反斜杠转义反斜杠。

print '\\'

答案 3 :(得分:5)

一种不加转义的反斜杠打印方法是将其字符代码传递给chr

>>> print(chr(92))
\

答案 4 :(得分:4)

尝试:

>>> s = r'Tea\coffee'
>>> s
'Tea\\coffee'
>>> print(s)
Tea\coffee
>>> print("\\")
\
>>> len("\\")
1

答案 5 :(得分:3)

你应该逃避它......用\

print '\\'

答案 6 :(得分:2)

Uses of escape character:
>>> print "\\"
output : \
print 'he\'s pythonic'
output : he's pythonic
"\" helps python to understand that in 'he\'s pythonic' , ['he's] not eol ..

答案 7 :(得分:1)

你可以这样做:

backslash = "\\"
print(backslash)
  

\

答案 8 :(得分:0)

你喜欢吗

print(fr"\{''}")

或者这个怎​​么样

print(r"\ "[0])
相关问题