How can I fill out a Python string with spaces?

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

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

    You can try this:

    print "'%-100s'" % 'hi'
    
    0 讨论(0)
  • 2020-11-22 07:29

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

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

    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:]
    
    0 讨论(0)
  • 2020-11-22 07:40

    Use Python 2.7's mini formatting for strings:

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

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

    0 讨论(0)
提交回复
热议问题