我想用空格填充字符串。我知道下面的方法适用于0:

>>> print  "'%06d'"%4
'000004'

但我想要这个的时候该怎么办呢?:

'hi    '

当然,我可以测量字符串长度和做str+" "*剩,但我想要最短的方式。


当前回答

从Python 3.6开始,你可以这样做

>>> strng = 'hi'
>>> f'{strng: <10}'

字面值字符串插值。

或者,如果你的填充大小是一个变量,就像这样(谢谢@Matt M.!):

>>> to_pad = 10
>>> f'{strng: <{to_pad}}'

其他回答

使用str.ljust ():

>>> 'Hi'.ljust(6)
'Hi    '

你还应该考虑string.zfill(), str.rjust()和str.center()来格式化字符串。它们可以被链接,并指定'fill'字符,如下所示:

>>> ('3'.zfill(8) + 'blind'.rjust(8) + 'mice'.ljust(8, '.')).center(40)
'        00000003   blindmice....        '

这些字符串格式化操作具有在Python v2和v3中工作的优点。

找个时间看看pydoc str:里面有很多好东西。

只要去掉0,它就会添加空格:

>>> print  "'%6d'"%4

你可以使用str.ljust(width[, fillchar]):

返回长度为width的字符串中左对齐的字符串。填充使用指定的fillchar(默认为空格)。如果width小于len(s)则返回原始字符串。

>>> 'hi'.ljust(10)
'hi        '

你也可以居中你的字符串:

'{0: ^20}'.format('nice')

你可以试试这个:

print "'%-100s'" % 'hi'