I want to fill out a string with spaces. I know that the following works for zero's:
>>> print "'%06d'"%4
'000004'
But what should I do when I want this?:
'hi '
of course I can measure string length and do str+" "*leftover
, but I'd like the shortest way.
codeforester
35.7k16 gold badges101 silver badges126 bronze badges
asked Apr 15, 2011 at 12:22
1
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 '
answered Apr 15, 2011 at 12:24
Felix KlingFelix Kling
769k171 gold badges1068 silver badges1114 bronze badges
5
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": >> strng = 'hi'
>>> f'{strng: >> [" " * 15 + x][-15:]
' string'
It requires knowing how long you want to pad to, of course, but it doesn't require measuring the length of the string you're starting with.
answered Sep 15, 2015 at 6:09
5
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:]
answered Jan 29, 2019 at 19:40
Erik AndersonErik Anderson
4,6153 gold badges29 silver badges28 bronze badges
2
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 '
answered Nov 23, 2018 at 13:34
2