【发布时间】:2013-11-18 10:39:07
【问题描述】:
以下按预期工作:
>>> print re.sub('(\w)"(\W)', r"\1''\2", 'The "raw string literal" is a special case of a "string literal".')
The "raw string literal'' is a special case of a "string literal''.
因为我想在 替换表达式 中使用单引号(这是正确的术语吗?),我使用双引号引用它。
但是为了我的启发,我尝试在 替换表达式中使用单引号,但无法理解结果:
>>> print re.sub('(\w)"(\W)', r'\1\'\'\2', 'The "raw string literal" is a special case of a "string literal".')
The "raw string literal\'\' is a special case of a "string literal\'\'.
这两种形式不应该产生完全相同相同的输出吗?
所以,我的问题是:
- 如何在单引号原始字符串中转义单引号?
- 如何在双引号原始字符串中转义双引号?
- 为什么在
re.sub()的第一个参数中我不必使用原始字符串,但在第二个参数中我必须使用。对于这个 Python 菜鸟来说,两者似乎都是正则表达式的字符串表示形式。
如果有影响,我在 Mac OS X(10.9,Mavericks)上使用 Python 2.7.5。
【问题讨论】: