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.