Python的 rjust()
、ljust()
、和 center()
方法是字符串类(str
)的内置方法,它们用于对文本进行对齐或居中。
-
rjust(width[, fillchar])
: 此方法返回一个新字符串,这是原始字符串右对齐,并通过填充足够数量的指定字符在原始字符串的左边来达到特定的宽度。如果 ‘fillchar’ 参数未提供,它将默认使用空格。代码示例:
text = "hello" print(text.rjust(10, '-')) # 输出:-----hello
-
center(width[, fillchar])
: 此方法返回一个新字符串,这是原始字符串居中,并通过填充足够数量的指定字符在原始字符串的两侧来达到特定的宽度。如果 ‘fillchar’ 参数未提供,它将默认使用空格。代码示例:
text = "hello" print(text.center(10, '-')) # 输出:--hello---
以上代码示例将会创建新的字符串,原始字符串"hello"右对齐或居中,并通过填充 ‘-’ 来达到10个字符的长度。
如果提供的宽度小于原始字符串的长度,那么这些方法将返回未修改的原始字符串。例如:
text = "hello"
print(text.rjust(3, '-')) # 输出:hello
print(text.center(3, '-')) # 输出:hello
以上代码因为指定的宽度3小于"hello"的长度,所以返回的是未修改的"hello"。