[英]What's the difference between r'string' and normal 'string' in python?
What's the difference between r string ( r'foobar'
) and normal string ( 'foobar'
) in python? r'foobar'
r字符串( r'foobar'
)和普通字符串( 'foobar'
)有什么区别? Is r'string' a regex string? r'string'是正则表达式字符串吗?
I've tried the following and there isn't any effects on my regex matches: 我尝试了以下操作,但对正则表达式匹配没有任何影响:
>>> 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']
r
doesn't signify a "regex string"; r
不表示“正则表达式字符串”; it means "raw string". 它的意思是“原始字符串”。 As per the docs : 根据文档 :
String literals may optionally be prefixed with a letter
'r'
or'R'
; 字符串文字可以选择以字母'r'
或'R'
开头; such strings are called raw strings and use different rules for interpreting backslash escape sequences. 这样的字符串称为原始字符串,并使用不同的规则来解释反斜杠转义序列。
The difference would become apparent in cases when you have backslash escapes: 当您使用反斜杠转义符时,区别将变得明显:
>>> 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'
Quoting from 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. 这避免了转义的需要,并产生了更清晰的字符串。
You might also want to refer to Lexical Analysis . 您可能还需要参考词法分析 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.