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

Ric*_*ano 3 python string.format

我想将一个字符串填充到一定长度,具体取决于变量的值,我想知道是否有一种标准的Pythonic方法可以使用string.format 迷你语言来完成.现在,我可以使用字符串连接:

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

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

我试过这个方法:

print(("{:-<{{padded_length}}}".format(padded_length = 10)).format("abc"))
Run Code Online (Sandbox Code Playgroud)

但它引发了一个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
Run Code Online (Sandbox Code Playgroud)

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

Ned*_*der 5

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

padded_length = 5
print("abc".rjust(padded_length, "-"))
Run Code Online (Sandbox Code Playgroud)

打印:

--abc
Run Code Online (Sandbox Code Playgroud)


Joh*_*ooy 5

print(("\n{:-<{}}").format("abc", padded_length))
Run Code Online (Sandbox Code Playgroud)

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

print(("{{:-<{padded_length}}}".format(padded_length=10)).format("abc"))
Run Code Online (Sandbox Code Playgroud)