Search code examples
pythonpython-3.xformattingf-string

How to use string.len() function inside f-string formatting?


How do I get len() to work inside Python f-string formatting?

for key, value in dictionary.items():
    (f'{key:<(len(key)+2)}<->{value:>4}\n')

Solution

  • In your specific case, you want to write key left-aligned in a field of length two larger than the length of key itself:

    f'{key:<(len(key)+2)}'  # wrong syntax, copied from the question
    

    ... assuming that key is a string, that can be done more simply by adding two spaces after key:

    f'{key}  '
    

    In the general case (where key is not necessarily a string), do this:

    f'{key:<{len(key)+2}}'  # correct syntax