How can I fill out a Python string with spaces?

前端 未结 13 1437
忘掉有多难
忘掉有多难 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条回答
  •  -上瘾入骨i
    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.

提交回复
热议问题