【问题标题】:string formatting not working as expected字符串格式未按预期工作
【发布时间】:2020-12-04 01:46:45
【问题描述】:

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

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

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

【问题讨论】:

    标签: python formatting maxlength


    【解决方案1】:

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

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

    如果切片超过了字符串的长度,Python 只会返回整个字符串,所以即使字符串比你的最大长度短,这也可以工作。

    【讨论】:

    • 这正是我所需要的。不敢相信这是这么简单的事情。非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    • 1970-01-01
    相关资源
    最近更新 更多