编程语言
首页 > 编程语言> > 是否有更多的Pythonic方法使用string.format将字符串填充到可变长度?

是否有更多的Pythonic方法使用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索引超出范围异常:

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,string-format
来源: https://codeday.me/bug/20190715/1469622.html