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

不想你离开。 提交于 2019-12-06 05:12:00
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"))
Ned Batchelder

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-------'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!