首页 > 解决方案 > 字符串格式未按预期工作

问题描述

我正在尝试格式化字符串以适合以下方式打印:

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

任何有关为什么会发生这种情况的帮助将不胜感激。

标签: pythonformattingmaxlength

解决方案


如果您只是想以最大长度截断列,则可以在附加它们之前使用字符串切片:

description = description[:23]
amount = amount[:7]
transactions.append(f'{description}{amount}')

如果切片超过了字符串的长度,Python 只会返回整个字符串,因此即使字符串比您的最大长度短,它也会起作用。


推荐阅读