I just have to write this down because that's the rule; if I find myself googling something basic like this more than once, it's worth blogging about.

Suppose you have a string and you want to pad with empty spaces. You have 2 options:


>>> s = "peter"
>>> s.ljust(10)
'peter     '
>>> f"{s:<10}"
'peter     '

The f-string notation is often more convenient because it can be combined with other formatting directives.
But, suppose the number 10 isn't hardcoded like that. Suppose it's a variable:


>>> s = "peter"
>>> width = 11
>>> s.ljust(width)
'peter      '
>>> f"{s:<width}"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Invalid format specifier

Well, the way you need to do it with f-string formatting, when it's a variable like that is this syntax:


>>> f"{s:<{width}}"
'peter      '

Comments

Eric

I think if its really only padding and you don't need any other f-string features: The built-in string method is the way to go!

The f-string stuff looks like a voodoo meta language :/ Sadly I also taught myself some of the %-notation magic.
We should celebrate explicitness wherever we can.

Option 3: `f'{s.ljust(width)}'` 😉

Your email will never ever be published.

Previous:
How to bulk-insert Firestore documents in a Firebase Cloud function September 23, 2021 Node, Firebase, JavaScript
Next:
Brotli compression quality comparison in the real world December 1, 2021 Node, JavaScript
Related by category:
How I run standalone Python in 2025 January 14, 2025 Python
get in JavaScript is the same as property in Python February 13, 2025 Python
How to resolve a git conflict in poetry.lock February 7, 2020 Python
Best practice with retries with requests April 19, 2017 Python
Related by keyword:
How to pad/fill a string by a variable in Python using f-strings January 24, 2020 Python
How do you thousands-comma AND whitespace format a f-string in Python March 17, 2024 Python
Format thousands in Python February 1, 2019 Python