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

StackOverflow https://stackoverflow.com/questions/11388180

  •  19-06-2021
  •  | 
  •  

سؤال

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.

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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-------'
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top