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

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

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

'hi    '

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


当前回答

博士TL;

text = 'hi'
print(f'{text:10}') # 'hi        '

更详细的解释

从Python3.6开始,可以使用f-strings文字插补。

变量空间:

value = 4
space = 10

# move value to left
print(f'foo {value:<{space}} bar') # foo 4          bar
# move value to right
print(f'foo {value:>{space}} bar') # foo          4 bar
# center value
print(f'foo {value:^{space}} bar') # foo     4      bar

恒定的空间:

value = 4

# move value to left
print(f'foo {value:<10} bar') # foo 4          bar
# move value to right
print(f'foo {value:>10} bar') # foo          4 bar
# center value
print(f'foo {value:^10} bar') # foo     4      bar

如果你想用其他char then space填充,在开头指定它:

value = 4
space = 10
padd = '_'

print(f'foo {value:{padd}^{space}} bar') # foo ____4_____ bar
print(f'foo {value:_^10} bar')           # foo ____4_____ bar

其他回答

你可以试试这个:

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

使用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:里面有很多好东西。

正确的方法是使用官方文档中描述的Python格式语法

对于这种情况,它将简单地为: {10} .format(“嗨”) 输出: “嗨”

解释:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
fill        ::=  <any character>
align       ::=  "<" | ">" | "=" | "^"
sign        ::=  "+" | "-" | " "
width       ::=  integer
precision   ::=  integer
type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

你所需要知道的就是这些^。

更新: 从python 3.6开始,字面值字符串插值更加方便!

foo = 'foobar'
print(f'{foo:10} is great!')
# foobar     is great!

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

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

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

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

字面值字符串插值。

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

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