Python String rjust() 方法,顾名思义,会将字符串的右对齐到其右侧的一定长度。任何字符(字母、数字或符号)都添加到字符串的开头(执行填充),具体取决于字符串移动的位数或确定的最大长度。但是,如果填充后的字符串长度小于原始字符串长度,则 method 不会对字符串进行任何更改。
此方法与 ljust() 方法相对应;因为 ljust() 将字符串对齐到其左侧。
语法
以下是 Python String rjust() 方法的语法 -
str.rjust(width[, fillchar])
参数
- width − 这是填充后的总字符串长度。
- fillchar − 这是填充字符;它是可选的,其默认值为空格字符。
返回值
此方法返回以 length width 字符串对齐的字符串。使用指定的 fillchar 完成填充(默认为空格)。如果 width 小于 len(s),则返回原始字符串。
例当我们将总字符串长度和数字传递给 fillchar 参数时,该方法将两端对齐的字符串返回到其右侧
以下示例显示了 Python String rjust() 方法的用法。在这里,我们创建了一个字符串 “this is string example....wow!!“,并通过传递 50 和 '0' 作为 width 和 fillchar 参数来调用方法 rjust()。
str = "this is string example....wow!!!";
print(str.rjust(50, '0'))
当我们运行上述程序时,它会产生以下结果——
例
当我们将字符串总长度作为 width 传递,将字母作为 fillchar 参数传递时,该方法将对齐的字符串返回到其右侧
str = "qikepu";
print(str.rjust(14, '#'))
给定程序的输出显示如下 -
例
如果我们尝试将多个字符作为 fillchar 参数传递,此方法将生成错误。
str = "qikepucom";
print(str.rjust(20, '#$$'))
给定程序的输出显示如下 -
File "main.py", line 2, in
print(str.rjust(20, '#$$'))
TypeError: The fill character must be exactly one character long
例
当我们只将 width 作为参数传递时,该方法使用默认的 fillchar (空格) 返回其右侧的对齐字符串
在给定的示例程序中,我们将创建一个字符串输入,并将字符串总长度作为参数传递给该方法。由于未指定 optional 参数,因此采用默认值 space。
str = "qikepucom";
print(str.rjust(25))
给定程序的输出显示如下 -
qikepucom
例
当传递的 width 参数小于字符串的长度时,该方法返回原始字符串
在给定的示例程序中,我们通过将 width 和 fillchar 参数传递给方法来创建字符串。但是,传递的 width 参数小于字符串的原始长度。返回值将作为原始字符串获取。
str = "qikepucom";
print(str.rjust(5, '$'))
给定程序的输出显示如下 -
qikepucom