[issue39601] brace escapes are not working in formatted string literal format specifications

Eric V. Smith report at bugs.python.org
Tue Feb 11 02:18:24 EST 2020


Eric V. Smith <eric at trueblade.com> added the comment:

I always use datetime for testing such things. Its __format__() returns its argument, as long as you don't have '%' in it.

I do agree that it's odd that the doubled braces cause the expression to be evaluated, but are still kept as single braces in the resulting string. I'll have to investigate, although I'm not sure if we can change it at this point. Surely someone, somewhere is relying on this behavior.

I'll assume that what the OP wants in my example below is a format specifier of "x{x}x":

>>> x = 42
>>> import datetime
>>> now = datetime.datetime.now()

>>> f'{now:x{{x}}x}'
'x{42}x'

Given the current behavior, I'm not sure it's possible to get 'x{x}x'. Sometimes nested f-strings will help, but I don't think that will work here. The OP might need to use a separate expression to calculate the format specifier, which I realize isn't a very satisfying solution.

>>> spec = 'x{x}x'
>>> f'{now:{spec}}'
'x{x}x'

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue39601>
_______________________________________


More information about the Python-bugs-list mailing list