我想用空格填充字符串。我知道下面的方法适用于0:
>>> print "'%06d'"%4
'000004'
但我想要这个的时候该怎么办呢?:
'hi '
当然,我可以测量字符串长度和做str+" "*剩,但我想要最短的方式。
我想用空格填充字符串。我知道下面的方法适用于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!
其他回答
你可以使用str.ljust(width[, fillchar]):
返回长度为width的字符串中左对齐的字符串。填充使用指定的fillchar(默认为空格)。如果width小于len(s)则返回原始字符串。
>>> 'hi'.ljust(10)
'hi '
你可以使用列表理解,这也会给你一个关于空格数量的想法,这将是一行。
"hello" + " ".join([" " for x in range(1,10)])
output --> 'hello '
正确的方法是使用官方文档中描述的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 2.7的字符串迷你格式:
'{0: <8}'.format('123')
这是左对齐,用' '字符填充到8个字符。