本文共 2630 字,大约阅读时间需要 8 分钟。
python中rjust
Python string API provides two utility function to create a new string of specified length from the source string with right and left justification.
Python字符串API提供了两个实用程序函数,可以使用左右对齐从源字符串创建指定长度的新字符串。
This function returns a new string of specified length with right-justified source string. We can specify the character to use for the padding, the default is whitespace. If the specified length is smaller than the source string, then the source string is returned.
此函数返回指定长度的新字符串,并带有右对齐的源字符串。 我们可以指定用于填充的字符,默认为空白。 如果指定的长度小于源字符串,则返回源字符串。
Let’s look at some examples of rjust() function.
让我们看一下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}***')
Output:
输出:
*** Hello******###############Hello******çççççççççççççççHello******Hello***
Python string ljust() is very similar to the rjust() function. The only difference is that the original string is right-justified. Let’s have a look at some examples.
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}***')
Output:
输出:
***Hello ******Hello###############******Helloççççççççççççççç******Hello***
If you want center-aligned string then you can use function.
如果要居中对齐的字符串,则可以使用函数。
Let’s see some error scenarios that may come when using rjust() and ljust() functions.
让我们看看使用rjust()和ljust()函数时可能出现的一些错误情况。
s.ljust('#')s.rjust('#')
Error: TypeError: ‘str’ object cannot be interpreted as an integer
错误: TypeError:“ str”对象无法解释为整数
>>> s.ljust()Traceback (most recent call last): File "", line 1, in TypeError: ljust() takes at least 1 argument (0 given)>>> >>> s.rjust()Traceback (most recent call last): File " ", line 1, in TypeError: rjust() takes at least 1 argument (0 given)>>>
>>> s.ljust(20, '#$')Traceback (most recent call last): File "", line 1, in TypeError: The fill character must be exactly one character long>>> >>> s.rjust(20, '#$')Traceback (most recent call last): File " ", line 1, in TypeError: The fill character must be exactly one character long>>>
Official Documentation: ,
官方文档: ,
翻译自:
python中rjust
转载地址:http://kmmzd.baihongyu.com/