2

What does r prefix followed by three single (or double) quotes, namely r''' ''', mean in Python? And when to use it? Could you explain further the following examples?

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

Related SO posts:

  1. The difference between three single quote'd and three double quote'd docstrings in python
  2. r prefix in Python regex

This question is not a duplicate. A direct and concise answer should be there in SO knowledge-base to make the community better.

Community
  • 1
  • 1
DehengYe
  • 569
  • 6
  • 22

3 Answers3

4

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.

Avinash Raj
  • 160,498
  • 22
  • 182
  • 229
2

''' can span strings which are multiline.

Like

x="""hey 
     hi"""

Here x will have \n even though you didn't put it. You can also include '" inside .

StephenTG
  • 2,449
  • 3
  • 23
  • 35
vks
  • 63,206
  • 9
  • 78
  • 110
2

Not just in regular expressions, if you want to declare multiline string you need to use triple quote notation.

E.g.:-

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

"""
hspandher
  • 13,259
  • 1
  • 23
  • 41