How to string pad a string in Python with a variable

19 October 2021   1 comment   Python

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      '



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.

Related posts