I often find myself Googling for this. Always a little bit embarrassed that I can't remember the incantation (syntax).
Suppose you have a string mystr
that you want to fill with with spaces so it's 10 characters wide:
>>> mystr = 'peter'
>>> mystr.ljust(10)
'peter '
>>> mystr.rjust(10)
' peter'
Now, with "f-strings" you do:
>>> mystr = 'peter'
>>> f'{mystr:<10}'
'peter '
>>> f'{mystr:>10}'
' peter'
What also trips me up is, suppose that the number 10
is variable. I.e. it's not hardcoded into the f-string but a variable from somewhere else. Here's how you do it:
>>> width = 10
>>> f'{mystr:<{width}}'
'peter '
>>> f'{mystr:>{width}}'
' peter'
What I haven't figured out yet, is how you specify a different character than a simple single whitespace. I.e. does anybody know how to do this, but with f-strings:
>>> width = 10
>>> mystr.ljust(width, '*')
'peter*****'
UPDATE
First of all, I left two questions unanswered. One was how do you make the filler something other than ' '
. The answer is:
>>> f'{"peter":*<10}'
'peter*****'
The question question was, what if you don't know what the filler character should be. In the above example, *
was hardcoded inside the f-string. The solution is stunningly simple actually.
>>> width = 10
>>> filler = '*'
>>> f'{"peter":{filler}<{width}}'
'peter*****'
But note, it has to be a single length string. This is what happens if you try to make it a longer string:
>>> filler = 'xxx'
>>> f'{"peter":{filler}<{width}}'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Invalid format specifier
Comments
Post your own commentf'{"peter":*<10}'
I think I misunderstood. It doesn't appear to be possible do a dynamic fill with f-strings. E.g., `f'{name}:{filler}<{length}'` doesn't work, nor does `f'{name}:{filler}<10'` or `f'{name}:*>{length}'`. I've tried doing this before and gave up.
Okay, how about this:
>>> name = 'peter'
>>> filler = '*'
>>> length = 10
>>> f = f'{filler}<{length}'
>>> f'{name:{f}}'
'peter*****'
Fill character in f-String:
f'{mystr:*<{width}}'
Hi,
> I.e. does anybody know how to do this, but with f-strings:
The answer is simple:
>>> mystr = 'peter'
>>> f'{mystr:*<10}'
'peter*****'
You put the fill character after the : but just before the < or >, like this: f"{mystr:*>{width}}".
Hi, at least it works with a different single char instead of a whitespace...
>>> mystr = "hello"
>>> f'{mystr:<10}'
'hello '
>>> f'{mystr:X<10}'
'helloXXXXX'
>>> foo = 'XYZ'
>>> f'{mystr:{foo}<10}'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Invalid format specifier
You can pad with a character by doing the following (the padding character must come before the direction and length): f"{mystr:*<10}" # Yields 'peter****'
Thank you so much, I've been searching for this for a while!