根据固定长度填充或截断字符串

etm*_*124 4 python string string-formatting

目前有类似的代码;

print '{: <5}'.format('test')
Run Code Online (Sandbox Code Playgroud)

' '如果小于5个字符,这将填充我的字符串.如果字符串超过5个字符,我需要截断字符串.

在格式化之前没有明确检查我的字符串的长度,是否有更好的方法来填充小于固定长度或截断如果大于固定长度?

Psi*_*dom 11

您可以使用5.5结合截断和填充,使得输出将永远是五个长度:

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

'{:5.5}'.format('test')
# 'test '
Run Code Online (Sandbox Code Playgroud)


Chr*_*nds 5

您可以使用str.ljust并对字符串进行切片:

>>> 'testsdf'.ljust(5)[:5]
'tests'
>>> 'test'.ljust(5)[:5]
'test '
Run Code Online (Sandbox Code Playgroud)