How can I fill out a Python string with spaces?

前端 未结 13 1675
忘掉有多难
忘掉有多难 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              '
    

提交回复
热议问题