How to format raw string with different expressions inside?

Peter Varo picture Peter Varo · May 26, 2013 · Viewed 22.6k times · Source

Let's say, we want to catch something with regex, using rawstring to define the pattern, which pattern has repeating elements, and variables inside. And we also want to use the format() string formatting form. How to do this?

import re
text = '"""!some text'
re.findall(r'"{3}{symbol}some\stext'.format(symbol='!'), text)

But this line leads us to an IndexError:

# IndexError: tuple index out of range

So, my question is: how to format a raw string if it has formatting curly-braces expression, and repeating curly-braces expression inside?

Thanks in advance!

Answer

Daniel Malachov picture Daniel Malachov · Oct 10, 2019

Use f-strings (introduced in Python 3.6):

a = 15
print(fr'Escape is here:\n but still {a}')

# => Escape is here:\n but still 15