在 IDLE(Python 的集成开发和学习环境)中,表达式值的表示回显到标准输出。
正如https://docs.python.org/3/library/idle.html 解释的那样:
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
同样,有多种方法可以得到一个带有两个连续斜杠的字符串:
>>> 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
我们可以确认hitman_str只有一个斜线:
>>> hitman_str.count(single_slash1)
1
我们可以遍历字符串并打印每个字符及其 Unicode 代码点。
正如预期的那样,这仅显示一个斜线:
>>> 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
有关更多信息,包括需要注意的转义序列列表,请参阅https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals