在Python中逃脱引用

时间:2013-06-19 18:57:19

标签: python escaping backslash

我正在尝试运行命令:

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

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

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

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

2 个答案:

答案 0 :(得分: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.'))无效,因为您会有引用问题。

答案 1 :(得分:0)

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

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

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