在字符串文字前面加上“r”是什么意思?意思是?
我第一次看到它用于跨多行构建正则表达式,作为 re.compile() 的方法参数,因此我假设 r 代表 RegEx。
例如:
regex = re.compile(
r'^[A-Z]'
r'[A-Z0-9-]'
r'[A-Z]$', re.IGNORECASE
)
那么在这种情况下 r
意味着什么?为什么我们需要它?
I first saw it used in building regular expressions across multiple lines as a method argument to re.compile()
, so I assumed that r
stands for RegEx.
For example:
regex = re.compile(
r'^[A-Z]'
r'[A-Z0-9-]'
r'[A-Z]
So what does r
mean in this case? Why do we need it?
, re.IGNORECASE
)
So what does r
mean in this case? Why do we need it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
r
表示该字符串将被视为原始字符串,这意味着所有转义码都将被忽略。例如:
'\n'
将被视为换行符,而r'\n'
将被视为字符\
随后是n
。来源:Python 字符串文字
The
r
means that the string is to be treated as a raw string, which means all escape codes will be ignored.For an example:
'\n'
will be treated as a newline character, whiler'\n'
will be treated as the characters\
followed byn
.Source: Python string literals
这意味着转义不会被翻译。例如:
是一个带有反斜杠后跟字母
n
的字符串。 (如果没有r
,它将是一个换行符。)b
确实代表字节字符串,并在 Python 3 中使用,其中字符串默认为 Unicode。在 Python 2.x 中,字符串默认是字节字符串,您可以使用u
来指示 Unicode。It means that escapes won’t be translated. For example:
is a string with a backslash followed by the letter
n
. (Without ther
it would be a newline.)b
does stand for byte-string and is used in Python 3, where strings are Unicode by default. In Python 2.x strings were byte-strings by default and you’d useu
to indicate Unicode.