The Python Oracle

How can I fill out a Python string with spaces?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Ocean Floor

--

Chapters
00:00 How Can I Fill Out A Python String With Spaces?
00:20 Answer 1 Score 96
00:29 Accepted Answer Score 1008
00:51 Answer 3 Score 612
01:12 Answer 4 Score 226
01:53 Thank you

--

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

--

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