How can I fill out a Python string with spaces?

前端 未结 13 1573
忘掉有多难
忘掉有多难 2020-11-22 07:13

I want to fill out a string with spaces. I know that the following works for zero\'s:

>>> print  \"\'%06d\'\"%4
\'000004\'

But wha

13条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 07:50

    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        ::=  
    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!
    

提交回复
热议问题