Allow f-string to dynamically pad spaces

Example:

# This works
>>> print(f"{3:4}")
'3   '
# However this does not work.
>>> pad_amount: int = ...
>>> print(f"3:pad_amount")
ValueError: Unknown format code 'a' for object of type 'int'  # I know this is the intended behavior, however the only other way to do this (or if you have better ways to do this please let me know) is using eval()

I am guessing you meant to include the curly braces in the second example (f"{3:pad_amount}")

The solution is to use another set of them. It’s not obvious that it would work, but it does! f"{3:{pad_amount}}"

2 Likes

Not too sure if this is the kind a ‘padding’ that you have in mind, but this script demonstrates ‘dynamic padding’ that is based on the maximum string length of a name in names:

names = ('Alice', 'Bob', 'Charlie')

pad = len(max(names, key=len))

for index, name in enumerate(names, 1):
    print(f"{name.ljust(pad, ' ')} : {index}")

[output]

Alice   : 1
Bob     : 2
Charlie : 3
1 Like