python中的r'string'和普通的'string'有什么区别?

2024-04-25 19:33:42 发布

您现在位置:Python中文网/ 问答频道 /正文

python中的r字符串(r'foobar')和普通字符串('foobar')有什么区别?r'string'是正则表达式字符串吗?在

我尝试了以下操作,但对我的正则表达式匹配没有任何影响:

>>> import re
>>> n = 3
>>> rgx = '(?=('+'\S'*n+'))'
>>> x = 'foobar'
>>> re.findall(rgx,x)
['foo', 'oob', 'oba', 'bar']
>>>
>>> rgx2 = r'(?=('+'\S'*n+'))'
>>> re.findall(rgx2,x)
['foo', 'oob', 'oba', 'bar']
>>>
>>> rgx3 = r'(?=(\S\S\S))'
>>> re.findall(rgx3,x)
['foo', 'oob', 'oba', 'bar']

Tags: 字符串importrestringfoobarfoobar区别
2条回答

在使用反斜杠转义符的情况下,这种区别将变得明显:

>>> s="foobar"
>>> import re
>>> re.sub('(o)\1', '', s)     # Using the backreference has no effect here as it's interpreted as a literal escaped 1
'foobar'
>>> re.sub(r'(o)\1', '', s)    # Using the backreference works!
'fbar'
>>> re.sub('(o)\\1', '', s)    # You need to escape the backslash here
'fbar'

引自String literal

A few languages provide a method of specifying that a literal is to be processed without any language-specific interpretation. This avoids the need for escaping, and yields more legible strings.

您可能还想引用Lexical Analysis。在

r不表示“regex string”;它的意思是“raw string”。根据the docs

String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for interpreting backslash escape sequences.

相关问题 更多 >