Tutorial Study Image

Python rjust()

Python 中的 rjust() 函数通过用指定字符填充给定最小长度来将字符串右对齐。如果缺少 fillchar 参数,则空格被视作默认填充字符。


string.rjust(width[, fillchar]) #where width is an integer value
 

rjust() 参数

rjust() 函数接受两个参数。fillchar 参数必须是单个字符。如果给定的 fillchar 参数包含多个字符,则会抛出 TypeError。

参数 描述 必需/可选
width 返回字符串的宽度 必需
填充字符 用于填充缺失空间的字符 可选

rjust() 返回值

返回值始终是一个字符串。这里,fillchar 字符填充在字符串的左侧。如果指定的宽度小于或等于字符串的长度,则返回原始字符串作为输出。

输入 返回值
如果参数 右对齐字符串

Python 中 rjust() 方法的示例

示例 1:如何在 Python 中右对齐最小宽度的字符串?


# example string
string = 'Python'
length = 7

# print right justified string
print(string.rjust(length))
 

输出


    Python

示例 2:如何在 Python 中右对齐字符串并填充剩余空间?


# example string
string = 'Python'
length = 10
fill = '*'

# print left justified string
print(string.rjust(length, fill))
 

输出


****Python