简体   繁体   English

Python正则表达式r前缀后跟三个单引号(或双引号)

[英]Python regular expression r prefix followed by three single (or double) quotes

What does r prefix followed by three single (or double) quotes , namely r''' ''' , mean in Python? 什么是r前缀后跟三个单引号(或双引号) ,即r''' ''' ,在Python中意味着什么? And when to use it? 什么时候使用它? Could you explain further the following examples? 你能进一步解释下面的例子吗?

foo = r'''foo'''
punctuation = r'''['“".?!,:;]'''

Related SO posts: 相关SO帖子:

  1. The difference between three single quote'd and three double quote'd docstrings in python python中三个单引号和三个双引号文档字符串之间的区别
  2. r prefix in Python regex Python正则表达式中的r前缀

This question is not a duplicate. 这个问题不重复。 A direct and concise answer should be there in SO knowledge-base to make the community better. 在SO知识库中应该有一个直接和简明的答案,以使社区更好。

If your pattern is surrounded by triple quotes, it won't need escaping of quotes present inside the regex. 如果您的模式被三重引号包围,则不需要转义正则表达式中存在的引号。

Simple one, 简单的,

r'''foo"'b'a'r"buzz'''

tough one which needs escaping. 艰难的,需要逃避。

r'foo"\'b\'a\'r"buzz'

This would be more helpful if your regex contain n number of quotes. 如果你的正则表达式包含n个引号,这将更有帮助。

Not just in regular expressions, if you want to declare multiline string you need to use triple quote notation. 不只是在正则表达式中,如果要声明多行字符串,则需要使用三重引号表示法。

Eg:- 例如:-

paragraph = """ It is  a paragraph
It is a graph
It is para

"""

''' can span strings which are multiline. '''可以跨越多行的字符串。

Like 喜欢

x="""hey 
     hi"""

Here x will have \\n even though you didn't put it. 这里x将有\\n即使你没有把它。 You can also include '" inside . 你也可以在里面加上'"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM