How can I fill out a Python string with spaces?

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

提交回复
热议问题