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

时间:2015-08-11 10:16:26

标签: python regex

r前缀后跟三个单引号(或双引号),即r''' ''',在Python中意味着什么?什么时候使用它?你能进一步解释下面的例子吗?

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

相关SO帖子:

  1. The difference between three single quote'd and three double quote'd docstrings in python
  2. r prefix in Python regex
  3. 这个问题不重复。在SO知识库中应该有一个直接和简明的答案,以使社区更好。

3 个答案:

答案 0 :(得分:4)

如果您的模式被三引号括起来,则不需要转义正则表达式中的引号。

简单的,

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

艰难的,需要逃避。

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

如果您的正则表达式包含n个引号,这会更有用。

答案 1 :(得分:3)

不只是在正则表达式中,如果要声明多行字符串,则需要使用三引号表示法。

E.g: -

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

"""

答案 2 :(得分:2)

'''可以跨越多行的字符串。

x="""hey 
     hi"""

即使你没有提出x \n,也会有'"。您还可以在其中加入<Control Id="InputField" Type="Edit" X="20" Y="100" Width="140" Height="18" Property="MachineIdNumber" Text="{80}"/>