目录
1. fill_character参数必须是字符或长度为1的字符串
描述
Python rjust()方法是字符串的排版方法,它将原字符串右对齐,并使用空格填充至指定长度,并返回新的字符串。如果指定的长度小于原字符串长度,则直接返回原字符串。
语法
str.rjust(width, fill_character)
参数说明
名称 | 说明 | 备注 |
width | 排版字符串宽度 | 整型参数 |
fill_character | 填充字符 | 可省略的字符参数,省略时默认等于空格符 |
返回值
rjust方法返回一个右对齐排版的字符串。
使用示例
1. 仅指定width参数
fill_character参数省略时,默认填充字符是空格:
>>> demo = "copyright"
>>> result = demo.rjust(50)
>>> id(demo)
4486574000
>>> id(result)
4487419464
>>> len(result)
50
>>> result
' copyright'
2. 指定填充字符
>>> demo = "huawei"
>>> result = demo.rjust(30, "*")
>>> result
'************************huawei'
注意事项
1. fill_character参数必须是字符或长度为1的字符串
fill_character必须是字符类型或者是长度为1的字符串,否则Python报错TypeError
>>> demo = "metadata"
>>> result = demo.rjust(30, "--")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: The fill character must be exactly one character long
2. 当字符串本身的长度不小于width值时
当字符串本身的长度大于或等于width的值时,rjust()方法返回原字符串。
>>> demo = "start"
>>> result = demo.rjust(1, "-")
>>> result
'start'
>>> id(demo)
4486464488
>>> id(result)
4486464488