582

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
  • 28,846
  • 11
  • 78
  • 104
taper
  • 7,340
  • 4
  • 24
  • 28
  • 1
    I know it might be deprecated in the future, but I still like this good old method: `"%-6s" % s` for left-aligned and `"%6s" % s` for right-aligned. – Basj Nov 26 '19 at 10:07

13 Answers13

800

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        '
Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
442

For a flexible method that works even when formatting complicated string, you probably should use the string-formatting mini-language, using either the str.format() method

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

of f-strings

>>> f'{"Hi": <16} StackOverflow!'  # Python >= 3.6
'Hi               StackOverflow!'
Steven C. Howell
  • 11,482
  • 11
  • 61
  • 79
simon
  • 12,663
  • 4
  • 40
  • 64
  • 15
    What if you have '16' in a variable? – Randy Jun 02 '14 at 16:54
  • I figured that out as well too. Should have posted it. The docs say this should work for Py2.6, but my findings are otherwise. Works in Py2.7 though. – Randy Jun 04 '14 at 04:01
  • 1
    I had problems with this type of formatting when I was using national accents. You would want 'kra' and 'krá' to be the same, but they were not. – quapka Oct 27 '14 at 10:46
  • 86
    @Randy `'{message: – CivFan Jan 25 '15 at 00:13
  • 24
    Don't use `str.format()` for templates with only a single `{...}` and nothing else. Just use the `format()` function and save yourself the parsing overhead: `format('Hi', '<16')`. – Martijn Pieters Jan 07 '18 at 16:29
  • I would suggest not making everyone who reads your code learn such a "mini language" - unless of course you wrap that logic in a function. – aaaaaa Mar 09 '19 at 16:38
  • @simon - I write readable functions regardless of what actual languages I use. But yes, I'm new to python and mainly write js. And just because something is standard doesn't mean you should make everyone parse your code. Regexes are terribly unfriendly to read and are far more standard than python's string formatting mini language. – aaaaaa Mar 11 '19 at 21:51
146

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              '
CivFan
  • 10,079
  • 9
  • 34
  • 55
82

You can try this:

print "'%-100s'" % 'hi'
abbot
  • 25,012
  • 5
  • 49
  • 56
72

Correct way of doing this would be to use Python's format syntax as described in the official documentation

For this case it would simply be:
'{:10}'.format('hi')
which outputs:
'hi '

Explanation:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
fill        ::=  <any character>
align       ::=  "<" | ">" | "=" | "^"
sign        ::=  "+" | "-" | " "
width       ::=  integer
precision   ::=  integer
type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

Pretty much all you need to know is there ^.

Update: as of python 3.6 it's even more convenient with literal string interpolation!

foo = 'foobar'
print(f'{foo:10} is great!')
# foobar     is great!
Azat Ibrakov
  • 7,007
  • 8
  • 31
  • 40
Granitosaurus
  • 17,068
  • 2
  • 45
  • 66
41

Use str.ljust():

>>> 'Hi'.ljust(6)
'Hi    '

You should also consider string.zfill(), str.ljust() and str.center() for string formatting. These can be chained and have the 'fill' character specified, thus:

>>> ('3'.zfill(8) + 'blind'.rjust(8) + 'mice'.ljust(8, '.')).center(40)
'        00000003   blindmice....        '

These string formatting operations have the advantage of working in Python v2 and v3.

Take a look at pydoc str sometime: there's a wealth of good stuff in there.

Johnsyweb
  • 121,480
  • 23
  • 172
  • 229
  • 1
    Thanks for pointing out the `str.center(n)` method. It was just what i was looking for and didn't even know its existance. :D – Luke Savefrogs Nov 01 '20 at 05:58
31

As of Python 3.6 you can just do

>>> strng = 'hi'
>>> f'{strng: <10}'

with literal string interpolation.

Or, if your padding size is in a variable, like this (thanks @Matt M.!):

>>> to_pad = 10
>>> f'{strng: <{to_pad}}'
WAF
  • 855
  • 3
  • 14
  • 30
  • 4
    `f'{strng: >10}'` for filling string with leading whitespace to a length of 10. That is magic. And it is not well documented. – Chang Ye Mar 24 '19 at 07:57
  • @changye I believe this is also the default behavior of `f'{strng:10}'`. – WAF Mar 24 '19 at 09:52
18

you can also center your string:

'{0: ^20}'.format('nice')
Remi
  • 17,911
  • 8
  • 51
  • 41
8

Use Python 2.7's mini formatting for strings:

'{0: <8}'.format('123')

This left aligns, and pads to 8 characters with the ' ' character.

aodj
  • 1,893
  • 1
  • 11
  • 11
5

Just remove the 0 and it will add space instead:

>>> print  "'%6d'"%4
eldarerathis
  • 32,541
  • 9
  • 86
  • 93
Amir Mofakhar
  • 5,859
  • 2
  • 12
  • 5
3

Wouldn't it be more pythonic to use slicing?

For example, to pad a string with spaces on the right until it's 10 characters long:

>>> x = "string"    
>>> (x + " " * 10)[:10]   
'string    '

To pad it with spaces on the left until it's 15 characters long:

>>> (" " * 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.

Zev Chonoles
  • 758
  • 5
  • 11
  • 1
    Can you elaborate on that? It's not that I don't believe you, I just want to understand why. – Zev Chonoles Oct 22 '15 at 15:16
  • 4
    Sure. The most pythonic way would be to use one of the builtin functions rather than using a homegrown solution as much as possible. – Mad Physicist Oct 22 '15 at 15:21
  • @MadPhysicist saying that slicing is less pythonic because you should use in built functions is like saying `''.join(reversed(str))` is more pythonic than `str[::-1]`, and we all know that's not true. – Nick Feb 15 '17 at 15:02
  • @NickA. That is not a very good analogy. The case you are using as an example is quite valid. However, `(x + " " * 10)[:10]` is in my opinion much more convoluted than using `x.ljust(10)`. – Mad Physicist Feb 15 '17 at 17:03
  • @MadPhysicist I more meant that your comment "The most pythonic way would be to use one of the builtin functions" is not **always** accurate and that they aren't words to live by. Although in this case it certainly is. – Nick Feb 15 '17 at 17:24
0

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:]
Erik Anderson
  • 4,041
  • 3
  • 26
  • 27
  • 1
    For some reason this is the funniest answer but I like it. Along those lines also consider: `min_len = 8` then `('hi' + ' '*min_len)[:min_len]` or `('0'*min_len + str(2))[-min_len]` – Poikilos Jan 25 '20 at 20:43
  • 1
    For the number, it would be `('0'*min_len + str(2))[-min_len:]` rather, though this is only for fun, and I recommend the other answers. – Poikilos Feb 28 '20 at 13:12
-4

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                 '
foobar666
  • 11
  • 2
  • ...and then you get a string that is 22 (len("hello")+17 :( ) characters long--that didn't go well. While we are being funny we could do `s = "hi"` ; `s + (6-len(s)) * " "` instead (it is ok when the result is negative). However, answers which use whatever framework feature that addresses the exact issue will be easier to maintain (see other answers). – Poikilos Jan 25 '20 at 20:58
  • Doesn't answer the question, the amount of space needed is unknown as str lengths vary. – misantroop Oct 10 '20 at 01:38