Python正則表達式 - r前綴任何人都可以解釋為什么下面的示例1有效,何時r不使用前綴?我認為r只要使用轉義序列,就必須使用前綴。示例2和示例3證明了這一點。# example 1import reprint (re.sub('\s+', ' ', 'hello there there'))# prints 'hello there there' - not expected as r prefix is not used# example 2import reprint (re.sub(r'(\b\w+)(\s+\1\b)+', r'\1', 'hello there there'))# prints 'hello there' - as expected as r prefix is used# example 3import reprint (re.sub('(\b\w+)(\s+\1\b)+', '\1', 'hello there there'))# prints 'hello there there' - as expected as r prefix is not used
3 回答

波斯汪
TA貢獻1811條經驗 獲得超4個贊
并非所有涉及反斜杠的序列都是轉義序列。\t
并且\f
是,例如,但\s
并非如此。在非原始字符串文字中,任何\
不屬于轉義序列的內容都被視為另一個\
:
>>> "\s"'\\s'>>> "\t"'\t'
\b
然而,是一個轉義序列,因此示例3失敗了。(是的,有些人認為這種行為很不幸。)
添加回答
舉報
0/150
提交
取消