Question

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.

Was it helpful?

Solution

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"))

OTHER TIPS

The following example should provide a solution for you.

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

prints:

--abc

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-------'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top