Pad or truncate string based on fixed length

微笑、不失礼 提交于 2019-12-01 08:12:19

You can use 5.5 to combine truncating and padding so that the output will always be of length of five:

'{:5.5}'.format('testsdf')
# 'tests'

'{:5.5}'.format('test')
# 'test '

You could use str.ljust and slice the string:

>>> 'testsdf'.ljust(5)[:5]
'tests'
>>> 'test'.ljust(5)[:5]
'test '
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!