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

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

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

'hi    '

当然,我可以测量字符串长度和做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: ^20}'.format('nice')

对于一个灵活的方法,即使在格式化复杂的字符串时也能工作,你可能应该使用字符串格式化迷你语言,

使用任意一个f字符串

>>> f'{"Hi": <16} StackOverflow!'  # Python >= 3.6
'Hi               StackOverflow!'

或者str.format()方法

>>> '{0: <16} StackOverflow!'.format('Hi')  # Python >=2.6
'Hi               StackOverflow!'

使用Python 2.7的字符串迷你格式:

'{0: <8}'.format('123')

这是左对齐,用' '字符填充到8个字符。

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

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

字面值字符串插值。

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

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

你可以试试这个:

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