-1

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')
3
  • @zvone: Yes for this particular example len() can be avoided, but in the general case it can't and this question is useful. Commented Jan 7, 2024 at 23:31
  • @smci you are commenting on my comment... but my answer below actually shows how to fix it in general case as well. Commented Jan 8, 2024 at 0:49
  • @zvone: fine, then all these comments can be deleted as no longer needed. Can you edit your answer so that the context "key left-aligned in space which is by two larger than the length of the key"? It sounds excessively specific if this answer is to stand for the general case of the syntax for using len() inside an f-string. Commented Jan 8, 2024 at 1:06

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.