When trying out some features with the new (and awesome) python 3 literal string interpolation, I found this weird difference.
For example, using the old str.format
, I can format integers with a dynamic number of digits like this:
>>> d = 5
>>> N = 3
>>> '{:0{N}d}'.format(d, N=N)
'005'
But when I try the equivalent using literal strings, I get an error:
>>> f'{:0{N}d}'
SyntaxError: f-string: empty expression not allowed
Only by swapping the order of the arguments do I get the correct formatting
>>> f'{d:0{N}}'
'005'
This struck me as odd since I assumed I could just swap to f-strings without modifying my strings, only the calls.
What are the syntactic differences between str.format
and f-string? And why does this example differ slightly?