[英]Does escaping work differently in Python shell? (Compared to code in file)
In a Python 3.7 shell I get some unexpected results when escaping strings, see examples below. 在Python 3.7 Shell中,转义字符串时会得到一些意外的结果,请参见下面的示例。 Got the same results in the Python 2.7 shell.
在python 2.7 shell中获得了相同的结果。
A quick read in the Python docs seems to say that escaping can be done in strings, but doesn't seem to say it can't be used in the shell. 快速阅读Python文档似乎表明转义可以在字符串中完成,但似乎并未说它不能在shell中使用。 (Or I have missed it).
(或者我错过了)。
Can someone explain why escaping doesn't seem to work as expected. 有人可以解释为什么转义似乎没有按预期进行。
Example one: 范例一:
input: >>> "I am 6'2\\" tall"
输入:
>>> "I am 6'2\\" tall"
output: 输出:
'I am 6\\'2" tall'
while >>> print("I am 6'2\\" tall")
而
>>> print("I am 6'2\\" tall")
returns (what I expected): 回报(我所期望的):
I am 6'2" tall
(I also wonder how the backslash, in the unexpected result, ends up behind the 6?) (我也想知道反斜杠在意外结果中如何最终落在6之后?)
Another example: 另一个例子:
input: >>> "\\tI'm tabbed in."
输入:
>>> "\\tI'm tabbed in."
output: "\\tI'm tabbed in."
输出:
"\\tI'm tabbed in."
When inside print() the tab is replaced with a proper tab. 在print()内部时,该选项卡将替换为适当的选项卡。 (Can't show it, because stackoverflow seems the remove the tab/spaces in front of the line I use inside a code block).
(无法显示它,因为stackoverflow似乎删除了我在代码块内使用的行前面的制表符/空格)。
The interactive shell will give you a representation of the return value of your last command. 交互式外壳将为您提供上一个命令的返回值的表示形式 。 It gives you that value using the
repr()
method, which tries to give a valid source code representation of the value; 它使用
repr()
方法为您提供该值,该方法试图给出该值的有效源代码表示形式 ; ie something you could copy and paste into code as is. 即,您可以按原样复制并粘贴到代码中的内容。
print
on the other hand prints the contents of the string to the console, without regards whether it would be valid source code or not. print
,另一方面输出字符串到控制台的内容,而不考虑是否将是有效的源代码或没有。
Basically your terminal is calling repr magic method of the string when you enter it in terminal as is. 基本上,当您按原样在终端中输入字符串时,终端会调用字符串的repr magic方法。 In the same time when you call
print
over the string it calls __str__
method on it: 在您通过字符串调用
print
,它在其上调用__str__
方法:
s = "I am 6'2\" tall"
s.__repr__()
'\'I am 6\\\'2" tall\''
s.__str__()
'I am 6\'2" tall'
See more on that comparison between those two methods: str vs. repr and that SO Difference between __str__ and __repr__? 有关这两种方法之间的比较,请参见更多内容: str vs. repr以及__str__和__repr__之间的 SO 差异? question.
题。
Good Lack in your future python adventures. 祝您未来的python冒险好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.