DehengYe
DehengYe

Reputation: 629

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? 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.

Upvotes: 2

Views: 822

Answers (3)

vks
vks

Reputation: 67978

''' 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 .

Upvotes: 2

hspandher
hspandher

Reputation: 16753

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

"""

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174786

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.

Upvotes: 4

Related Questions