Pad or truncate string based on fixed length

前端 未结 2 1710
囚心锁ツ
囚心锁ツ 2021-01-12 21:06

Currently have code that looks something like;

print \'{: <5}\'.format(\'test\')

This will pad my string with \' \' if it i

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-12 21:52

    You could use str.ljust and slice the string:

    >>> 'testsdf'.ljust(5)[:5]
    'tests'
    >>> 'test'.ljust(5)[:5]
    'test '
    

提交回复
热议问题