如何用空格填充 Python 字符串?
- 2024-12-05 08:38:00
- admin 原创
- 126
问题描述:
我想用空格填充字符串。我知道以下方法适用于零:
>>> print("'%06d'"%4)
'000004'
但是当我想要这个时我该怎么办呢?:
'hi '
当然我可以测量字符串长度并这样做str+" "*leftover
,但我喜欢最短的方法。
解决方案 1:
您可以使用以下方式执行此操作str.ljust(width[, fillchar])
:
返回长度为width的字符串中左对齐的字符串。使用指定的填充字符(默认为空格)进行填充。如果width小于,则返回原始字符串
len(s)
。
>>> 'hi'.ljust(10)
'hi '
解决方案 2:
对于在格式化复杂字符串时也能使用的灵活方法,您可能应该使用字符串格式化微语言,
使用f 字符串
>>> f'{"Hi": <16} StackOverflow!' # Python >= 3.6
'Hi StackOverflow!'
或str.format()
方法
>>> '{0: <16} StackOverflow!'.format('Hi') # Python >=2.6
'Hi StackOverflow!'
解决方案 3:
字符串格式方法让你可以用嵌套的关键字参数做一些有趣的事情。最简单的情况是:
>>> '{message: <16}'.format(message='Hi')
'Hi '
如果要16
作为变量传递:
>>> '{message: <{width}}'.format(message='Hi', width=16)
'Hi '
如果您想传递整个套件和 kaboodle的变量:
'{message:{fill}{align}{width}}'.format(
message='Hi',
fill=' ',
align='<',
width=16,
)
结果是(你猜对了):
'Hi '
对于所有这些,你可以使用python 3.6+ f 字符串:
message = 'Hi'
fill = ' '
align = '<'
width = 16
f'{message:{fill}{align}{width}}'
当然结果是:
'Hi '
解决方案 4:
您可以尝试以下操作:
print("'%-100s'" % 'hi')
解决方案 5:
正确的做法是使用官方文档中描述的 Python 格式语法
对于这种情况,它将简单得多:
'{:10}'.format('hi')
输出:
'hi '
解释:
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!
解决方案 6:
使用str.ljust()
:
>>> 'Hi'.ljust(6)
'Hi '
您还应该考虑使用string.zfill()
、str.rjust()
和str.center()
来进行字符串格式化。这些可以链接起来并指定“填充”字符,因此:
>>> ('3'.zfill(8) + 'blind'.rjust(8) + 'mice'.ljust(8, '.')).center(40)
' 00000003 blindmice.... '
这些字符串格式化操作具有在 Python v2 和 v3 中工作的优势。
有时看一下pydoc str
:里面有很多好东西。
解决方案 7:
总结
text = 'hi'
print(f'{text:10}') # 'hi '
详细解释
因为Python3.6
您可以使用 f 字符串文字插值。
变量空间:
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
如果要用空格填充其他字符,请在开头指定:
value = 4
space = 10
padd = '_'
print(f'foo {value:{padd}^{space}} bar') # foo ____4_____ bar
print(f'foo {value:_^10} bar') # foo ____4_____ bar
解决方案 8:
从 Python 3.6 开始,你可以这样做
>>> strng = 'hi'
>>> f'{strng: <10}'
使用文字字符串插值。
或者,如果您的填充大小是一个变量,如下所示(感谢@Matt M.!):
>>> to_pad = 10
>>> f'{strng: <{to_pad}}'
解决方案 9:
您还可以将字符串居中:
'{0: ^20}'.format('nice')
解决方案 10:
使用 Python 2.7 的字符串迷你格式:
'{0: <8}'.format('123')
它左对齐,并用“ ”字符填充到 8 个字符。
解决方案 11:
只需删除 0,它就会添加空格:
>>> print("'%6d'"%4)
解决方案 12:
使用切片不是更符合 Python 风格吗?
例如,在字符串右侧填充空格,直到其长度达到 10 个字符:
>>> x = "string"
>>> (x + " " * 10)[:10]
'string '
在左侧填充空格,直到其长度达到 15 个字符:
>>> (" " * 15 + x)[-15:]
' string'
当然,它需要知道您想要填充的长度,但它不需要测量您开始的字符串的长度。
解决方案 13:
由于其他答案中没有提到,我想指出您可以使用strings
方法来确定文本的正确性。
您至少有三个选择:
左对齐:
>>> "left justified".ljust(30, "*")
left justified****************
右对齐:
>>> "right justified".rjust(30, "*")
***************right justified
居中对齐
>>> "center justified".center(30, "*")
*******center justified*******
我正在使用 python 3.10.13,但我相信它在大多数 3.X python 版本中都可以运行。
解决方案 14:
一个可以代替各种打印格式的好技巧:
(1)向右填充空格:
('hi' + ' ')[:8]
(2)在左侧填充前导零:
('0000' + str(2))[-4:]
在 Python 中不推荐使用这种方法,但对于缺乏高质量文本格式化功能的语言和宏来说,这种逻辑很有用。:)
解决方案 15:
您可以使用列表推导来完成此操作,这也会让您了解空格的数量,并且只需一行。
"hello" + " ".join([" " for x in range(1,10)])
output --> 'hello '