How can I fill out a Python string with spaces?

693,925

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

Solution 2

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

Solution 3

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              '

Solution 4

You can try this:

print "'%-100s'" % 'hi'

Solution 5

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!
Share:
693,925
taper
Author by

taper

Updated on July 08, 2022

Comments

  • taper
    taper almost 2 years

    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.

    • Basj
      Basj over 4 years
      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.
  • taper
    taper about 13 years
    print "'%-6s'" % 'hi' indeed!!
  • Felix Kling
    Felix Kling about 13 years
    @simon already gave this answer... why posting a duplicate answer?
  • aodj
    aodj about 13 years
    I didn't click the 'new responses have been posted, click to refresh' and so missed it.
  • CoatedMoose
    CoatedMoose almost 11 years
    @simon 's answer is more flexible and more useful when formatting more complex strings
  • CoatedMoose
    CoatedMoose almost 11 years
    or @abbot 's if you are stuck supporting old versions of python
  • Randy
    Randy about 10 years
    What if you have '16' in a variable?
  • Randy
    Randy about 10 years
    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.
  • sunshinekitty
    sunshinekitty almost 10 years
    @simon as someone stuck on a python2.5 system this answer helped me, not a useless answer +1
  • quapka
    quapka over 9 years
    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.
  • Mawg says reinstate Monica
    Mawg says reinstate Monica over 9 years
    ljust() is now deprecated. See stackoverflow.com/questions/14776788/… for the correct way to do it
  • radtek
    radtek over 9 years
    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
  • CivFan
    CivFan over 9 years
    @Randy '{message: <{fill}}'.format(message='Hi', fill='16')
  • Seppo Erviälä
    Seppo Erviälä over 9 years
    Not deprecated any more in 3.3+
  • Max Tsepkov
    Max Tsepkov about 9 years
    I like this common printf syntax much better. Allows you to write complex strings without countless concatenations.
  • Rohan Grover
    Rohan Grover almost 9 years
    ljust(), rjust() have been deprecated from the string module only. They are available on the str builtin type.
  • Zev Chonoles
    Zev Chonoles over 8 years
    Can you elaborate on that? It's not that I don't believe you, I just want to understand why.
  • Mad Physicist
    Mad Physicist over 8 years
    Sure. The most pythonic way would be to use one of the builtin functions rather than using a homegrown solution as much as possible.
  • Nick stands with Ukraine
    Nick stands with Ukraine over 7 years
    @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.
  • Mad Physicist
    Mad Physicist over 7 years
    @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).
  • Nick stands with Ukraine
    Nick stands with Ukraine over 7 years
    @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.
  • Martijn Pieters
    Martijn Pieters over 6 years
    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').
  • Eric Blum
    Eric Blum about 6 years
    For completeness, "'%+100s'" % 'hi' would work for putting spaces to the right of 'hi'
  • aaaaaa
    aaaaaa over 5 years
    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
    aaaaaa over 5 years
    @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.
  • Chang Ye
    Chang Ye over 5 years
    f'{strng: >10}' for filling string with leading whitespace to a length of 10. That is magic. And it is not well documented.
  • WAF
    WAF over 5 years
    @changye I believe this is also the default behavior of f'{strng:10}'.
  • Poikilos
    Poikilos over 4 years
    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
    Poikilos over 4 years
    ...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
    Poikilos over 4 years
    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.
  • ak_slick
    ak_slick about 4 years
    How would you handle varying the message as well? msgs = ['hi', 'hello', 'ciao']
  • CivFan
    CivFan about 4 years
    @ak_slick You can pass in variables instead of hard-coded values into the format function.
  • misantroop
    misantroop over 3 years
    Doesn't answer the question, the amount of space needed is unknown as str lengths vary.
  • Luke Savefrogs
    Luke Savefrogs over 3 years
    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
  • kva1966
    kva1966 over 2 years
    Today, this should be preferred to the other approaches.
  • LogicDaemon
    LogicDaemon over 2 years
    @aaaaaa readability is subjective. I liked this answer a lot, it's very concise and clear.
  • aaaaaa
    aaaaaa over 2 years
    Yes it's subjective, but some code is more easily learned than others which is what I consider to be "readable". I think the best way to learn what makes code readable is to work with junior devs or first time coders. Regex may be considered concise and clear to a few, but the majority have a hard time reading and understanding it.