有人能解释为什么下面的例子1工作,当 r前缀没有使用?
我认为在使用转义序列时必须使用 r前缀。
示例2和示例3演示了这一点。
# example 1
import re
print (re.sub('\s+', ' ', 'hello     there      there'))
# prints 'hello there there' - not expected as r prefix is not used
# example 2
import re
print (re.sub(r'(\b\w+)(\s+\1\b)+', r'\1', 'hello     there      there'))
# prints 'hello     there' - as expected as r prefix is used
# example 3
import re
print (re.sub('(\b\w+)(\s+\1\b)+', '\1', 'hello     there      there'))
# prints 'hello     there      there' - as expected as r prefix is not used
 
                                
                             
                                
                             
                                
                             
                                
                            