python - 如何用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)
...但我很好奇是否有更“优雅”的方式来做这件事,比如字符串格式。
这甚至可能吗?
谢谢!
解决方案
您可以在 python 中使用字符串对象的ljust()
和:rjust()
customer = 'John Doe'
balance = 39.99
output = customer.ljust(15, '.') + str(balance).rjust(10, '.')
print(output)
#John Doe............39.99
根据您需要的格式,您可以通过更改宽度或添加空格字符来调整它。
推荐阅读
- rust - 我可以使用 FlatBuffers 遍历所有表格项吗?
- excel - 当一列中有 36 个“1”时,通过单元格颜色进行识别
- c# - Monogame,如何画一个按钮<
- python - 在 python 中从分页 API 中提取数据时,是否正在努力使用循环附加所有页面中的数据?
- python - 如何遍历 sparql 中的列表
- r - 在 R 中按组查找和总结时间戳之间同时发生的事件
- react-native-firebase - 为什么在为 Web 应用程序记录时,参与时间不记录反应本机应用程序中的自定义事件
- html - 如何使容器内的项目居中?
- xcode - 在 XCode 中快速打开后如何使选项卡永久化?
- html - 是否可以检测到 display:inline-block 元素是否已被 CSS 压缩到新行,以便我可以为其分配新设计?