rjust()
方法使用指定字符将字符串右对齐到给定宽度。
示例
text = 'Python'
# right aligns 'Python' up to width 10 using '*'
result = text.rjust(10, '*')
print(result)
# Output: ***Python
rjust() 语法
rjust()
方法的语法是
string.rjust(width,[fillchar])
在这里,rjust()
使用 fillchar 将 string 右对齐到 width。
rjust() 参数
rjust()
方法可以接受两个参数
- width - 给定字符串的宽度
- fillchar(可选)- 用于填充宽度剩余空间的字符
注意:如果 width 小于或等于字符串的长度,则返回原始字符串。
rjust() 返回值
rjust()
方法返回
- 右对齐的字符串,宽度为给定 width。
示例 1:Python 字符串 rjust()
text = 'programming'
# right aligns text up to length 15 using '$'
result = text.rjust(15, '$')
print(result)
输出
$$$$programming
在上面的示例中,我们使用 rjust()
方法右对齐了 text 字符串。
在这里,text.rjust(15, '$')
使用指定的填充字符 '$'
将 text 字符串,即 'programming'
,右对齐到宽度 15。
该方法返回字符串 '$$$$programming'
,其宽度为 15。
示例 2:使用默认 fillchar 的 rjust()
text = 'cat'
# passing only width and not specifying fillchar
result = text.rjust(7)
print(result)
输出
cat
在这里,我们没有传入 fillchar,因此 rjust
方法采用默认填充字符,即空格。
这里 text.rjust(7)
在使用空格将字符串 'cat'
右对齐到宽度 7 后返回 ' cat'
。
示例 3:当 width 小于或等于字符串长度时的 rjust()
如果 width 小于或等于字符串的长度,则 rjust()
方法返回原始字符串。例如,
text = 'Ninja Turtles'
# width equal to length of string
result1 = text.rjust(13, '*')
print(result1)
# width less than length of string
result2 = text.rjust(10, '*')
print(result2)
输出
Ninja Turtles Ninja Turtles
在这里,我们传入了 width
- 13 - 等于 text 的长度
- 10 - 小于 text 的长度
在这两种情况下,rjust()
方法都返回原始字符串 'Ninja Turtles'
。
另请阅读