Python f-strings: how to escape curly brackets with numbers in it

Question:

If you have to escape curly brackets in f-strings you can double them, so {{hello}} results in {hello}.
The problem is, that the algorithm just concatenates the string and afterwards interprets this part as every other part. So if there is any structure inside this string, that triggers some f-string behaviour it fails.

For example, if you want to insert a string with a RegExp like this

_date = f'''
SELECT 
    acol,
    substring(full_date , '[0-9]{{4}}')         
FROM 
    dates 
'''

it results in the desired result. The f-string is instantly converted, so the pattern changes to

substring(full_date , '[0-9]{4}') 

as needed for the SQL query.

But this string as input of

_date.format(acol=acol)

to insert the acol variable, fails with:

IndexError: Replacement index 4 out of range for positional args tuple

Because the {4} is always interpreted as index for a replacement. And it does not matter in which way the {4} is inserted. Because this makes no difference for the format algorithm.

Is there any solution, for instance prevent the format algorithm from interpreting this string part?

Asked By: Nils Pitapatting

||

Answers:

Unless there are more constraints you haven’t mentioned, this just doesn’t have to be an f-string at all:

_date = '''
SELECT 
    {acol},
    substring(full_date , '[0-9]{{4}}')         
FROM 
    dates 
'''

formatted = _date.format(acol="some_col")

print(formatted)

prints


SELECT 
    some_col,
    substring(full_date , '[0-9]{4}')         
FROM 
    dates 
Answered By: isaactfa
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.