问题
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