Python字符串rjust()和ljust()
时间:2020-02-23 14:43:30 来源:igfitidea点击:
Python字符串API提供了两个实用程序函数,可以使用左右对齐从源字符串创建指定长度的新字符串。
Python字符串rjust()
此函数返回指定长度的新字符串,并带有右对齐的源字符串。
我们可以指定用于填充的字符,默认为空白。
如果指定的长度小于源字符串,则返回源字符串。
让我们看一下rjust()函数的一些示例。
s = 'Hello' s1 = s.rjust(20) print(f'***{s1}***') s1 = s.rjust(20, '#') print(f'***{s1}***') s1 = s.rjust(20, 'ç') print(f'***{s1}***') s1 = s.rjust(4) print(f'***{s1}***')
输出:
*** Hello*** ***###############Hello*** ***çççççççççççççççHello*** ***Hello***
如果您不熟悉f前缀的字符串格式,请阅读Python中的f字符串。
Python字符串ljust()
Python字符串ljust()与rjust()函数非常相似。
唯一的区别是原始字符串是右对齐的。
让我们看一些例子。
s = 'Hello' s1 = s.ljust(20) print(f'***{s1}***') s1 = s.ljust(20, '#') print(f'***{s1}***') s1 = s.ljust(20, 'ç') print(f'***{s1}***') s1 = s.ljust(4) print(f'***{s1}***')
输出:
***Hello *** ***Hello###############*** ***Helloççççççççççççççç*** ***Hello***
如果您想要居中对齐的字符串,则可以使用Python字符串center()函数。
使用rjust()和ljust()函数的错误方案
让我们看看使用rjust()和ljust()函数时可能出现的一些错误情况。
s.ljust('#') s.rjust('#')
错误:TypeError:" str"对象无法解释为整数
>>> s.ljust() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: ljust() takes at least 1 argument (0 given) >>> >>> s.rjust() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: rjust() takes at least 1 argument (0 given) >>>
>>> s.ljust(20, '#$') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: The fill character must be exactly one character long >>> >>> s.rjust(20, '#$') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: The fill character must be exactly one character long >>>