Search code examples
pythonregexstring-formatting

Formatting raw string in Python when using exact match regex


The fr prefix can combine f and r flag.
But when it comes to the regex's exact match, it seems that it can't format the raw string well:

import re

RE1 = r'123'
RE2 = re.compile(fr'@{3} {RE1}')

Then, the RE2.pattern will become '@3 123',

but what I want is '@{3} 123'.


Solution

  • You have to escape the braces surrounding the 3 like this, otherwise they will be interpreted as string interpolation:

    import re
    
    RE1 = r'123'
    RE2 = re.compile(fr'@{{3}} {RE1}')
    print(RE2)
    

    This produces:

    @{3} 123
    

    Ref: https://www.python.org/dev/peps/pep-0498/

    Note that the correct way to have a literal brace appear in the resulting string value is to double the brace:

    >>> f'{{ {4*10} }}'
    '{ 40 }'
    >>> f'{{{4*10}}}'
    '{40}'