How can I fill out a Python string with spaces?

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

提交回复
热议问题