3

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.

3 Answers 3

5
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"))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. And here was me thinking I had read the documentation thoroughly enough when the answer was quite clear.
5

The following example should provide a solution for you.

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

prints:

--abc

Comments

2

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-------'

1 Comment

Ah, that makes sense. I wasn't thinking through which brackets needed to be escaped clearly enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.