python - 是否有更 Pythonic 的方法来使用 string.format 将字符串填充为可变长度?

标签 python string.format

我想根据变量的值将字符串填充到一定长度,我想知道是否有标准的 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

除了字符串连接之外,是否有标准的内置方法来执行此操作?第二种方法应该有效,所以我不确定为什么会失败。

最佳答案

print(("\n{:-<{}}").format("abc", padded_length))

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

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

关于python - 是否有更 Pythonic 的方法来使用 string.format 将字符串填充为可变长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11388180/

相关文章:

python - 如何使用 pandas 中的 groupby 计算绝对总和?

python - Healpy 可以计算双谱来研究 CMB 图的非高斯性吗?

python - 根据匹配值从不同的 Dataframe 更新 Dataframe

c# - 如何让 String.Format 不解析 {0}

c# - 形成Json格式字符串

Python GUI 应用分发 : written in wxPython, TKinter 或 QT

python - 使用 tkinter 在 GUI 中创建一个 Box

.net - 在 String.Format() 中转义单引号

c# - 使用 String.Format 为所有占位符指定小数位

java - 如何通过从列表中获取参数来使用 String.format 创建字符串