How is it possible to encode """ (triple quotes) into a raw string?

2k views Asked by At

How do I encode """ in a raw python string?

The following does not seem to work:

string = r"""\"\"\""""

since when trying to match """ with a regular expression, I have to double-escape the character ": Returns an empty list:

string = r"""\"\"\""""
regEx = re.compile(r"""
        (\"\"\")
""", re.S|re.X)
result = re.findall(regEx, string)

in this case result is an empty list. This same regular expression returns ['"""'] when I load a string with """ from file content.

Returns double-escaped quotations:

string = r"""\"\"\""""
regEx = re.compile(r"""
        (\\"\\"\\")
""", re.S|re.X)
result = re.findall(regEx, string)

now result is equal to ['\\"\\"\\"']. It want it to be equal to ['"""'].

2

There are 2 answers

0
Marcelo Cantos On BEST ANSWER

In general, there are three options:

  1. Don't use the r prefix. That's just a convenience to avoid excessive use of double-backslashes in regexes. It isn't required.
  2. Use r'…', inside which the " character isn't special.
  3. Mix and match r"…" and '':, e.g. pattern = '"""' + r"\s*\d\d-'\d\d'-\d\d\s*" + '"""'

In this instance, you can do both 1 and 2: single quotes and no r prefix.

1
BrenBarn On

The simplest way is to just do '"""'.