python - 字符串格式未按预期工作
问题描述
我正在尝试格式化字符串以适合以下方式打印:
Payday 1000.00
groceries -50.00
dinner out wit -175.00
bacon, eggs, & -50.00
total: 725
为此,我使用字符串格式。左侧列('description')的最大长度不能超过 23 个字符,右侧的列('amount')不能超过 7 个字符的最大长度。
这是我到目前为止的代码:
def __str__(self):
balance = 0
transactions = []
nl = '\n'
header = self.category.center(30, '*')
for item in self.ledger:
transaction = item['amount']
balance += transaction
item['amount'] = '{:.2f}'.format(item['amount'])
description = '{:.<23}'.format(item['description'])
amount = '{:.>7}'.format(item['amount'])
transactions.append(f'{description}{amount}')
total = f'Total: {balance}'
return f"{header}\n{nl.join(tuple(transactions))}\n{total}"
有了上面的内容,大部分情况下一切正常,但是我的字符串都没有受到最大长度的限制,我不知道为什么。
以下是我按原样运行此代码时的结果:
*************Food*************
Payday.................1000.00
groceries...............-50.00
dinner out with friends-175.00
bacon, eggs, vegetables, fruits and salad for breakfast.-50.00
Total: 725
任何有关为什么会发生这种情况的帮助将不胜感激。
解决方案
如果您只是想以最大长度截断列,则可以在附加它们之前使用字符串切片:
description = description[:23]
amount = amount[:7]
transactions.append(f'{description}{amount}')
如果切片超过了字符串的长度,Python 只会返回整个字符串,因此即使字符串比您的最大长度短,它也会起作用。
推荐阅读
- linux - 我将如何编写一个“if”命令来检查是否有多个参数?
- android-studio - 在 Android 上颤振火焰精灵复制而不是在 iPhone 上?
- javascript - 如何在地图缩放上交换图层可见性?
- javascript - 如何以方形空间形式提醒上传文件的文件名?
- xcode - 打开新项目后 Xcode 立即崩溃
- javascript - 如何重构拖放文件 Chrome 扩展以解决 CORB 错误
- prolog - Prolog - 递归中的最大值
- linux - 在装配中打印新行
- python - 如何根据python中的索引将二维数组中的元素与另一个列表链接?
- php - Carbon 未找到 PHP 项目