如何使用Python将字符串填充为特定长度的n个字符

3
我很难找到准确的措辞来描述我的问题,因为我刚开始接触格式化字符串。
假设我有两个变量:
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)

...但我很好奇有没有更加“优雅”的方法,例如使用字符串格式化。

这种方法可行吗?

谢谢!

3个回答

6
您可以在Python中使用字符串对象的ljust()rjust()方法:
customer = 'John Doe'
balance = 39.99

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

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

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


1
谢谢您的帮助!这对我很有用,而且最终结果非常干净简洁。 - MWhizzy

1
如果您不希望在点的两侧有空格,就像其他答案所建议的那样,您可以通过指定格式来实现同样的效果。
"{:.<17s}{:.>8.2f}".format(customer, balance)

需要左对齐17个字符宽度的字符串,右侧用.填充,以及精确到小数点后两位的8个字符右对齐、左侧用.填充的浮点数。

在f-string(Python >=3.6)中可以使用相同方式:

f"{customer:.<17s}{balance:.>8.2f}"

然而,如果你想在点号两侧也包括空格,情况会更加复杂。你仍然可以这样做,但需要在填补空白之前进行双倍填充/格式化或连接:
"{:.<16s}{:.>9s}".format(f"{customer} ", f" {balance:>.2f}")

但是我有点犹豫称之为更加优雅。

您也可以通过格式设置来完成所有这些操作:

# Fill in with calculated number of "."
"{} {} {:.2f}".format(customer,
                      "."*(25 - (2 + len(customer) + len(f"{balance:.2f}"))),
                      balance)
# Similarly used for calculated width to pad with "."
"{} {:.^{}s} {:.2f}".format(customer,
                            "",
                            25 - (2 + len(customer) + len(f"{balance:.2f}")),
                            balance)

但是,再次说,更优雅的确实不是。

它可能不太优雅,但它确实帮助我了解和学习了一些格式化的知识,这真是太棒了!我非常感谢详细的答案,它非常有帮助。最终,我使用了Aminrd的解决方案,因为它简单且符合我的需求,但我很高兴你也分享了你的想法。 - MWhizzy

0
我很惊讶没有人提到f-strings;毫无疑问,这是Python版本大于等于3.6中最优雅的方式。
output = f'{customer:.<25} {balance:.2f}'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接