Question

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 ['"""'].

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top