>>> r'\'
File "<stdin>", line 1
r'\'
^
SyntaxError: EOL while scanning string literal
>>> r'\\'
'\\\\'
>>> r'\\\'
File "<stdin>", line 1
r'\\\'
^
SyntaxError: EOL while scanning string literal
Run Code Online (Sandbox Code Playgroud)
似乎解析器可以将原始字符串中的反斜杠视为常规字符(不是原始字符串的全部内容吗?),但我可能遗漏了一些明显的东西.TIA!
我不理解python正则表达式中scape运算符\的功能以及原始字符串的r'的逻辑。一些帮助表示赞赏。
码:
import re
text=' esto .es 10 . er - 12 .23 with [ and.Other ] here is more ; puntuation'
print('text0=',text)
text1 = re.sub(r'(\s+)([;:\.\-])', r'\2', text)
text2 = re.sub(r'\s+\.', '\.', text)
text3 = re.sub(r'\s+\.', r'\.', text)
print('text1=',text1)
print('text2=',text2)
print('text3=',text3)
Run Code Online (Sandbox Code Playgroud)
该理论说:反斜杠字符('\')表示特殊形式或允许使用特殊字符而无需调用特殊含义。
就此问题末尾提供的链接而言,r'表示原始字符串,即符号没有特殊含义,它保持不变。
所以在上面的正则表达式中,我希望text2和text3是不同的,因为替换文本是'。'。在文本2中,即句点,而(原则上)文本3中的替代文本为r'。这是一个原始字符串,即应显示的字符串,反斜杠和句点。但它们的结果相同:
结果是:
text0= esto .es 10 . er - 12 .23 with [ and.Other ] here is more ; puntuation
text1= esto.es 10. er- 12.23 with [ and.Other ] here is more; puntuation
text2= esto\.es 10\. er …Run Code Online (Sandbox Code Playgroud)