Search code examples
regexpython-3.xf-string

How to format f-strings with regex expressions?


I have a few strings that were originally concatenated with plus signs and included regex strings. Here's an example:

"Level 4: " + re.sub(r"(\w)([A-Z])", r"\1 \2", talents[1]) + "\n\n"

But, I've been meaning to use more proper formatting. I did some research on f-strings and I want to use them here. I tried it this way:

f'Level 4: {re.sub(r"(\w)([A-Z])", r"\1 \2", talents[1])} \n\n'

However, my editor is barking at me about expression fragments having backslashes. Are f-strings not the right tool for the job in this case?

Edit: As requested by @jwodder, here is the error I'm getting from Python (I'm on 3.6)

SyntaxError: f-string expression part cannot include a backslash

Solution

  • You cannot interpolate an expression with backslash in an f-string, and this is currently a restriction by design. You could separate this into two statements:

    subst = re.sub(r"(\w)([A-Z])", r"\1 \2", talents[1])
    msg = f'Level 4: {subst} \n\n'
    

    (Side note: There is currently a proposal (PEP 536) to relax such restriction to make the original code work as expected, but it is not accepted or implemented yet.)