首页 > 解决方案 > 如何用n个字符填充字符串以使其在Python中具有一定的长度

问题描述

我很难找到我的问题的确切措辞,因为我是格式化字符串的新手。

假设我有两个变量:

customer = 'John Doe'
balance = 39.99

我想打印一行 25 个字符宽,并用特定字符(在本例中为句点)填充两个值之间的空间:

'John Doe .......... 39.99'

所以当我遍历客户时,我想打印一行总是 25 个字符,他们的名字在左边,他们的余额在右边,并允许调整句点以填充它们之间的空间。

我可以将其分解为多个步骤并完成结果...

customer = 'Barry Allen'
balance = 99
spaces = 23 - len(customer + str(balance))
'{} {} {}'.format(customer, '.' * spaces, balance)

# of course, this assumes that len(customer + str(balance)) is less than 23 (which is easy to work around)

...但我很好奇是否有更“优雅”的方式来做这件事,比如字符串格式。

这甚至可能吗?

谢谢!

标签: pythonpython-3.xformattingstring-formatting

解决方案


您可以在 python 中使用字符串对象的ljust()和:rjust()

customer = 'John Doe'
balance = 39.99

output = customer.ljust(15, '.') + str(balance).rjust(10, '.')

print(output)
#John Doe............39.99

根据您需要的格式,您可以通过更改宽度或添加空格字符来调整它。


推荐阅读