How can I fill out a Python string with spaces?

How can I fill out a Python string with spaces?

You can do this with str.ljust(width[, fillchar]):

Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s).

>>> hi.ljust(10)
hi        

For a flexible method that works even when formatting complicated string, you probably should use the string-formatting mini-language,

using either f-strings

>>> f{Hi: <16} StackOverflow!  # Python >= 3.6
Hi               StackOverflow!

or the str.format() method

>>> {0: <16} StackOverflow!.format(Hi)  # Python >=2.6
Hi               StackOverflow!

How can I fill out a Python string with spaces?

The new(ish) string format method lets you do some fun stuff with nested keyword arguments. The simplest case:

>>> {message: <16}.format(message=Hi)
Hi             

If you want to pass in 16 as a variable:

>>> {message: <{width}}.format(message=Hi, width=16)
Hi              

If you want to pass in variables for the whole kit and kaboodle:

{message:{fill}{align}{width}}.format(
   message=Hi,
   fill= ,
   align=<,
   width=16,
)

Which results in (you guessed it):

Hi              

And for all these, you can use python 3.6+ f-strings:

message = Hi
fill =  
align = <
width = 16
f{message:{fill}{align}{width}}

And of course the result:

Hi              

Leave a Reply

Your email address will not be published. Required fields are marked *