【问题标题】:Is there a more Pythonic way to pad a string to a variable length using string.format?有没有更 Pythonic 的方法来使用 string.format 将字符串填充到可变长度?
【发布时间】:2012-07-09 01:33:23
【问题描述】:

我想将字符串填充到一定长度,具体取决于变量的值,我想知道是否有标准的 Pythonic 方法可以使用 string.format mini-language 来执行此操作。现在,我可以使用字符串连接:

padded_length = 5
print(("\n{:-<" + str((padded_length)) + "}").format("abc"))
# Outputs "abc--"

padded_length = 10
print(("\n{:-<" + str((padded_length)) + "}").format("abc"))
#Outputs "abc-------"

我试过这个方法:

print(("{:-<{{padded_length}}}".format(padded_length = 10)).format("abc"))

但它会引发IndexError: tuple index out of range 异常:

Traceback (most recent call last):
  File "<pyshell#41>", line 1, in <module>
    print(("{:-<{{padded_length}}}".format(padded_length = 10)).format("abc"))
IndexError: tuple index out of range

除了字符串连接之外,还有标准的内置方法吗?第二种方法应该有效,所以我不确定它为什么会失败。

【问题讨论】:

    标签: python string.format


    【解决方案1】:
    print(("\n{:-<{}}").format("abc", padded_length))
    

    你尝试的另一种方式,应该这样写

    print(("{{:-<{padded_length}}}".format(padded_length=10)).format("abc"))
    

    【讨论】:

    • 非常感谢。当答案很清楚时,我认为我已经足够彻底地阅读了文档。
    【解决方案2】:

    以下示例应该为您提供解决方案。

    padded_length = 5
    print("abc".rjust(padded_length, "-"))
    

    打印:

    --abc
    

    【讨论】:

      【解决方案3】:

      您需要转义最外面的大括号。以下对我来说很好:

      >>>'{{0:-<{padded_length}}}'.format(padded_length=10).format('abc')
      'abc-------'
      

      【讨论】:

      • 啊,有道理。我没有考虑清楚哪些括号需要转义。
      猜你喜欢
      • 2014-05-22
      • 1970-01-01
      • 2020-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      相关资源
      最近更新 更多