Python 3.x 如何在python中以字符串形式打印单个反斜杠?

Python 3.x 如何在python中以字符串形式打印单个反斜杠?,python-3.x,Python 3.x,在python中(3倍版本) r和r尝试了这两种方法,但都无效 尝试转义转义字符\,即'\\',但如果我正确理解了您的问题,则无法转义,例如:print(\\”?在IDLE(Python的集成开发和学习环境)中,表达式值的表示形式与stdout相呼应 正如所解释的那样: repr函数用于表达式值的交互式回显。 它返回控件所在的输入字符串的更改版本 代码、一些BMP代码点和所有非BMP代码点将被替换 有转义码 如果要打印字符串,请使用print()函数。否则您将得到它的表示形式 考虑输入IDLE的

在python中(3倍版本)

r
r
尝试了这两种方法,但都无效
尝试转义转义字符
\
,即
'\\'
,但如果我正确理解了您的问题,则无法转义,例如:
print(\\”

在IDLE(Python的集成开发和学习环境)中,表达式值的表示形式与stdout相呼应

正如所解释的那样:

repr
函数用于表达式值的交互式回显。 它返回控件所在的输入字符串的更改版本 代码、一些BMP代码点和所有非BMP代码点将被替换 有转义码

如果要打印字符串,请使用
print()
函数。否则您将得到它的表示形式

考虑输入IDLE的以下代码:

>>> hitman_str = "Agent \ 47"
>>> print(hitman_str) # We see only one slash when using print
Agent \ 47
>>> hitman_str # This shows the representation, which shows two slashes
'Agent \\ 47'
>>> print(repr(hitman_str)) # Same as above
'Agent \\ 47'
有多种方法可以获得只有一个斜杠的字符串:

single_slash1 = "\\"
>>> print(single_slash1)
\
>>> single_slash2 = "\ "[0]
>>> print(single_slash2)
\
>>> single_slash1 == single_slash2
True
>>> hitman_str.count(single_slash1)
1
>>> for char in hitman_str:
    print(char, ord(char))


A 65
g 103
e 101
n 110
t 116
  32
\ 92
  32
4 52
7 55
类似地,有多种方法可以获得带有两个连续斜杠的字符串:

>>> two_slashes1 = "\\\\"
>>> print(two_slashes1)
\\
>>> print(repr(two_slashes1))
'\\\\'
>>> two_slashes1
'\\\\'
>>> len(two_slashes1)
2
>>> two_slashes2 = r"\\"
>>> print(two_slashes2)
\\
>>> print(repr(two_slashes2))
'\\\\'
>>> two_slashes2
'\\\\'
>>> len(two_slashes2)
2
我们可以确认杀手只有一条斜线:

single_slash1 = "\\"
>>> print(single_slash1)
\
>>> single_slash2 = "\ "[0]
>>> print(single_slash2)
\
>>> single_slash1 == single_slash2
True
>>> hitman_str.count(single_slash1)
1
>>> for char in hitman_str:
    print(char, ord(char))


A 65
g 103
e 101
n 110
t 116
  32
\ 92
  32
4 52
7 55
我们可以遍历字符串并打印每个字符及其Unicode代码点。 正如预期的那样,这只显示一条斜线:

single_slash1 = "\\"
>>> print(single_slash1)
\
>>> single_slash2 = "\ "[0]
>>> print(single_slash2)
\
>>> single_slash1 == single_slash2
True
>>> hitman_str.count(single_slash1)
1
>>> for char in hitman_str:
    print(char, ord(char))


A 65
g 103
e 101
n 110
t 116
  32
\ 92
  32
4 52
7 55
原始字符串非常方便,特别是对于Windows路径,如果您不想使用
os.path
pathlib

>>> filename = r"C:\Users\Lee Hong\Documents\New Letters\Impatient 1999-06-14.txt" # Works fine
>>> filename = "C:\Users\Lee Hong\Documents\New Letters\Impatient 1999-06-14.txt" # Error
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
>>> raw_str = r"This \\\has \11 \\slashes \\and \no \line \break"
>>> print(raw_str)
This \\\has \11 \\slashes \\and \no \line \break
>>> raw_str.count(single_slash1)
11

有关更多信息,包括要注意的转义序列列表,请参阅

'\\'
如果有效,请发布实际代码,而不仅仅是您正在尝试的字符串。问题的可能重复项是模糊的,因为这显然会打印一个反斜杠,但它太简单了,因此有了问号。但它并没有像我预期的那样打印一个反斜杠。关于达尔文的更多信息,请键入“帮助”、“版权”、“信用证”或“许可证”,并选择3.7.3(默认,2019年3月27日,09:23:15)[Clang 10.0.1(Clang-1001.0.46.3)]打印(“\\”)\请查看我提供的图像,在第三个输入行中,我尝试了这个文字。我得到了它,我打印时没有使用打印功能