The Python Oracle

How can I fill out a Python string with spaces?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Ancient Construction

--

Chapters
00:00 Question
00:33 Accepted answer (Score 934)
01:01 Answer 2 (Score 546)
01:28 Answer 3 (Score 192)
02:25 Answer 4 (Score 87)
02:37 Thank you

--

Full question
https://stackoverflow.com/questions/5676...

Accepted answer links:
[str.ljust(width[, fillchar])]: http://docs.python.org/library/stdtypes....

Answer 2 links:
[string-formatting mini-language]: http://docs.python.org/2/library/string....
[f-strings]: https://www.python.org/dev/peps/pep-0498/
[str.format()]: https://docs.python.org/3/library/stdtyp...

Answer 3 links:
[string format method]: https://docs.python.org/2/library/string...
[whole kit and kaboodle]: https://docs.python.org/2/library/string...
[python 3.6+ f-strings]: https://docs.python.org/3/tutorial/input...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #stringformatting #pad

#avk47



ACCEPTED ANSWER

Score 1008


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        '



ANSWER 2

Score 612


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!'



ANSWER 3

Score 226


The 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              '



ANSWER 4

Score 96


You can try this:

print("'%-100s'" % 'hi')