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