How can I fill out a Python string with spaces?

前端 未结 13 1375
忘掉有多难
忘掉有多难 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:40

    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.

    0 讨论(0)
  • 2020-11-22 07:41

    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!'
    
    0 讨论(0)
  • 2020-11-22 07:43

    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.

    0 讨论(0)
  • 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        ::=  <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!
    
    0 讨论(0)
  • 2020-11-22 07:50

    you can also center your string:

    '{0: ^20}'.format('nice')
    
    0 讨论(0)
  • 2020-11-22 07:50

    Just remove the 0 and it will add space instead:

    >>> print  "'%6d'"%4
    
    0 讨论(0)
提交回复
热议问题