-2

我正在尝试运行命令:

'"Isn\'t," she said.'

输出是: "Isn\'t," she said.

为什么输出不是: "Isn't," she said.

任何人都知道这是什么规则?谢谢

4

2 回答 2

4

您会看到表示对象(reprstr)的两种不同方式之间的区别。

>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print '"Isn\'t," she said.'
"Isn't," she said.

在第一种情况下,python 默认使用repr-- 但是,print函数/语句str隐式使用。请注意,数据模型中建议了这两种方法之间的主要区别object.__repr__

如果可能的话,这应该看起来像一个有效的 Python 表达式,可用于重新创建具有相同值的对象(给定适当的环境)。

换句话说,你可以使用eval(repr('"Isn\'t," she said.'))它并且它会工作。(不能保证所有对象的这种行为,只是建议。由于字符串是如此简单的对象,它可以工作)。但是,eval(str('"Isn\'t," she said.'))这不起作用,因为您会遇到引用问题。

于 2013-06-19T19:03:09.700 回答
0

我唯一能想到的是您使用的是原始字符串,它在字符串中留下反斜杠并且不会将它们解释为转义字符。

print('"Isn\'t," she said.')
>>> "Isn't," she said.

print(r'"Isn\'t," she said.')
>>> "Isn\'t," she said.
于 2013-06-19T19:02:41.937 回答