796

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.

0

15 Answers 15

1026

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        '
6
  • 23
    @simon 's answer is more flexible and more useful when formatting more complex strings Commented Jul 27, 2013 at 7:08
  • 4
    or @abbot 's if you are stuck supporting old versions of python Commented Jul 27, 2013 at 7:25
  • 2
    ljust() is now deprecated. See stackoverflow.com/questions/14776788/… for the correct way to do it
    – Mawg
    Commented Jan 21, 2015 at 8:41
  • 1
    Its gone in python 3? Just wanted to add there is also rjust and center which work much the same way but for different alignments
    – radtek
    Commented Jan 22, 2015 at 13:37
  • 29
    ljust(), rjust() have been deprecated from the string module only. They are available on the str builtin type. Commented Jun 30, 2015 at 21:07
630

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!'
9
  • 36
    What if you have '16' in a variable?
    – Randy
    Commented Jun 2, 2014 at 16:54
  • 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
    Commented Oct 27, 2014 at 10:46
  • 106
    @Randy '{message: <{fill}}'.format(message='Hi', fill='16')
    – CivFan
    Commented Jan 25, 2015 at 0:13
  • 35
    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'). Commented Jan 7, 2018 at 16:29
  • 4
    @aaaaaa readability is subjective. I liked this answer a lot, it's very concise and clear. Commented Feb 17, 2022 at 6:41
235

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              '
2
  • How would you handle varying the message as well? msgs = ['hi', 'hello', 'ciao']
    – ak_slick
    Commented Apr 3, 2020 at 17:07
  • 1
    @ak_slick You can pass in variables instead of hard-coded values into the format function.
    – CivFan
    Commented Apr 3, 2020 at 18:32
98

You can try this:

print("'%-100s'" % 'hi')
5
  • print "'%-6s'" % 'hi' indeed!!
    – taper
    Commented Apr 15, 2011 at 12:44
  • 8
    @simon as someone stuck on a python2.5 system this answer helped me, not a useless answer +1 Commented Jul 5, 2014 at 11:49
  • 19
    Not deprecated any more in 3.3+ Commented Feb 16, 2015 at 11:23
  • 3
    I like this common printf syntax much better. Allows you to write complex strings without countless concatenations. Commented Jun 8, 2015 at 9:22
  • 6
    For completeness, "'%+100s'" % 'hi' would work for putting spaces to the right of 'hi'
    – Eric Blum
    Commented May 8, 2018 at 20:44
92

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

Use str.ljust():

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

You should also consider string.zfill(), str.rjust() 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.

1
  • 3
    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 Commented Nov 1, 2020 at 5:58
48

TL;DR

text = 'hi'
print(f'{text:10}') # 'hi        '

Longer explanation

Since Python3.6 you can use f-strings literal interpolation.

Variable space:

value = 4
space = 10

# move value to left
print(f'foo {value:<{space}} bar') # foo 4          bar
# move value to right
print(f'foo {value:>{space}} bar') # foo          4 bar
# center value
print(f'foo {value:^{space}} bar') # foo     4      bar

Constant space:

value = 4

# move value to left
print(f'foo {value:<10} bar') # foo 4          bar
# move value to right
print(f'foo {value:>10} bar') # foo          4 bar
# center value
print(f'foo {value:^10} bar') # foo     4      bar

If you want to padd with some other char then space, specify it at the beginning:

value = 4
space = 10
padd = '_'

print(f'foo {value:{padd}^{space}} bar') # foo ____4_____ bar
print(f'foo {value:_^10} bar')           # foo ____4_____ bar
2
  • 4
    Today, this should be preferred to the other approaches.
    – kva1966
    Commented Nov 10, 2021 at 21:21
  • I found this approach much betther than ljust/rjust alternatives. For example, assuming zip_code is an integer, the way to apply some formatting with rjust would be str(zip_code).rjust(3, "0"), instead the equivalent of this with this approach is f"{zip_code:0>3}". Small and more readable! Problem? slower.. *only if you care about this. (10% based on my tests) Commented Sep 17, 2022 at 20:24
40

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}}'
2
  • 8
    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
    Commented Mar 24, 2019 at 7:57
  • 1
    @changye I believe this is also the default behavior of f'{strng:10}'.
    – WAF
    Commented Mar 24, 2019 at 9:52
21

you can also center your string:

'{0: ^20}'.format('nice')
10

Use Python 2.7's mini formatting for strings:

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

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

2
  • 4
    @simon already gave this answer... why posting a duplicate answer? Commented Apr 15, 2011 at 13:25
  • 6
    I didn't click the 'new responses have been posted, click to refresh' and so missed it.
    – aodj
    Commented Apr 17, 2011 at 20:43
8

Just remove the 0 and it will add space instead:

>>> print("'%6d'"%4)
5

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.

5
  • 1
    Can you elaborate on that? It's not that I don't believe you, I just want to understand why. Commented Oct 22, 2015 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. Commented Oct 22, 2015 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. Commented Feb 15, 2017 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). Commented Feb 15, 2017 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. Commented Feb 15, 2017 at 17:24
5

Since it is not mentioned in other answers, I would like to point out that you can use strings methods for justificate text.

You have three options at least:

  • Left justified:
>>> "left justified".ljust(30, "*")
left justified****************
  • Right justified:
>>> "right justified".rjust(30, "*")
***************right justified
  • Center justified
>>> "center justified".center(30, "*")
*******center justified*******

I am using python 3.10.13, but I believe it works in most 3.X python versions.

3
  • This is what I want, and I tried it, but Python doesn't add the correct amount of padding. When I use 'EXAMPLE'.rjust(10, '*') then I just get EXAMPLE back, When I use 'EXAMPLE'.rjust(20, '*') then I get *******EXAMPLE back which is only 14 characters. When I use 'SHORT'.rjust(20, '*') then I get *******SHORT back which is 12 characters (even less). I expect all strings returned to be 20 characters long. Why is this happening?
    – HeatZync
    Commented Apr 19, 2024 at 11:27
  • 1
    Strange... because: when I do 'EXAMPLE'.rjust(10, '*'), I get '***EXAMPLE'. when I do 'EXAMPLE'.rjust(20, '*'), I get '*************EXAMPLE'. when I do 'SHORT'.rjust(20, '*'), I get '***************SHORT' and when I do len('SHORT'.rjust(20, '*')), I get 20 Which version of python are you using? I'm using Python 3.10.13
    – Ger
    Commented Jun 26, 2024 at 10:41
  • 1
    Your solution is very nice and works without issue for me. Commented Jan 13 at 22:47
3

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:]

This approach is not recommended in Python but the logic is useful for languages and macros that lack quality text formatting functions. :)

2
  • 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
    Commented Jan 25, 2020 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
    Commented Feb 28, 2020 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                 '
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
    Commented Jan 25, 2020 at 20:58
  • Doesn't answer the question, the amount of space needed is unknown as str lengths vary.
    – misantroop
    Commented Oct 10, 2020 at 1:38

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.