Pad or truncate string based on fixed length

前端 未结 2 1711
囚心锁ツ
囚心锁ツ 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:47

    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 '
    
    0 讨论(0)
  • 2021-01-12 21:52

    You could use str.ljust and slice the string:

    >>> 'testsdf'.ljust(5)[:5]
    'tests'
    >>> 'test'.ljust(5)[:5]
    'test '
    
    0 讨论(0)
提交回复
热议问题