Is there a more Pythonic way to pad a string to a variable length using string.format?

为君一笑 提交于 2019-12-07 12:24:40

问题


I want to pad a string to a certain length, depending on the value of a variable, and I'm wondering if there is a standard, Pythonic way to do this using the string.format mini-language. Right now, I can use string concatenation:

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

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

I tried this method:

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

but it raises an IndexError: tuple index out of range exception:

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

Is there a standard, in-built way to do this apart from string concatenation? The second method should work, so I'm not sure why it fails.


回答1:


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

The other way you were trying, should be written this way

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



回答2:


The following example should provide a solution for you.

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

prints:

--abc



回答3:


You need to escape the outer most curly brackets. The following works fine for me:

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


来源:https://stackoverflow.com/questions/11388180/is-there-a-more-pythonic-way-to-pad-a-string-to-a-variable-length-using-string-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!