如何在Python中用n个字符填充字符串以使其达到一定长度

MWh*_*zzy 3 python formatting string-formatting python-3.x

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

假设我有两个变量:

customer = 'John Doe'
balance = 39.99
Run Code Online (Sandbox Code Playgroud)

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

'John Doe .......... 39.99'
Run Code Online (Sandbox Code Playgroud)

因此,当我循环浏览客户时,我想打印一行始终为 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)
Run Code Online (Sandbox Code Playgroud)

...但我很好奇是否有一种更“优雅”的方式来做到这一点,例如字符串格式化。

这可能吗?

谢谢!

ami*_*nrd 6

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

customer = 'John Doe'
balance = 39.99

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

print(output)
#John Doe............39.99
Run Code Online (Sandbox Code Playgroud)

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