Python的ljust异常
Python的ljust()函数是用来对字符串进行左对齐的操作,如果使用不当可能会导致异常。
具体来说,ljust()函数的参数是一个整数,表示字符串的总长度,如果当前字符串长度小于总长度,则在字符串右侧填充空格使字符串长度达到总长度。如果当前字符串长度大于等于总长度,则不进行任何操作。
如果在调用ljust()函数时,指定的总长度小于等于当前字符串的长度,会导致函数返回一个与原字符串相同的字符串,但不会抛出异常。但是如果指定的总长度为负数或者不是整数类型,将会抛出TypeError异常。例如:
s = 'hello'
# 返回 'hello '
s = s.ljust(8)
# 抛出 TypeError: 'float' object cannot be interpreted as an integer
s = s.ljust(8.5)
# 抛出 TypeError: 'str' object cannot be interpreted as an integer
s = s.ljust('8')
原文地址: https://www.cveoy.top/t/topic/6cw 著作权归作者所有。请勿转载和采集!