I want to fill out a string with spaces. I know that the following works for zero\'s:
>>> print \"\'%06d\'\"%4
\'000004\'
But wha
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 '
You can try this:
print "'%-100s'" % 'hi'
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 '
You could do it using list comprehension, this'd give you an idea about the number of spaces too and would be a one liner.
"hello" + " ".join([" " for x in range(1,10)])
output --> 'hello '
A nice trick to use in place of the various print formats:
(1) Pad with spaces to the right:
('hi' + ' ')[:8]
(2) Pad with leading zeros on the left:
('0000' + str(2))[-4:]
Use Python 2.7's mini formatting for strings:
'{0: <8}'.format('123')
This left aligns, and pads to 8 characters with the ' ' character.