【问题标题】:How to fill string with n character to make it a certain length in Python如何用n个字符填充字符串以使其在Python中具有一定的长度
【发布时间】:2020-03-04 00:56:26
【问题描述】:

我很难找到我的问题的确切措辞,因为我是格式化字符串的新手。

假设我有两个变量:

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 python-3.x formatting string-formatting


    【解决方案1】:

    可以在python中使用ljust()rjust()的字符串对象:

    customer = 'John Doe'
    balance = 39.99
    
    output = customer.ljust(15, '.') + str(balance).rjust(10, '.')
    
    print(output)
    #John Doe............39.99
    

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

    【讨论】:

    • 感谢您的帮助!这对我有用,结果非常干净和简单。
    【解决方案2】:

    如果您不想像其他答案所建议的那样在点的两侧有空格,您也可以实现 specifying formatting

    "{:.<17s}{:.>8.2f}".format(customer, balance)
    

    17 个字符宽左对齐,. 右填充字符串和 8 个字符右对齐,. 左填充,浮点数精度为 2 个小数点。

    您可以使用 f 字符串 (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 的解决方案,因为它很简单并且可以满足我的需求,但我很高兴你也分享了它。
    猜你喜欢
    • 2018-06-14
    • 2013-09-27
    • 2015-11-04
    • 2021-11-30
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 2021-09-23
    • 2013-12-17
    相关资源
    最近更新 更多