Python3 笔记:ljust、rjust 和 center
1、ljust() 方法返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。
ljust(self, width, fillchar=' ', /)
width -- 指定字符串长度。
fillchar -- 填充字符,默认为空格。
str1 = 'sentence'
str2 = 'word'
print(str1.ljust(20))
print(str2.ljust(20))
"""
运行结果:
sentence
word
"""
2、rjust() 返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。如果指定的长度小于字符串的长度则返回原字符串。
rjust(self, width, fillchar=' ', /)
width -- 指定字符串长度。
fillchar -- 填充字符,默认为空格。
str1 = 'sentence'
str2 = 'word'
print(str1.rjust(20))
print(str2.rjust(20))
"""
运行结果:sentenceword
"""
3、center() 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。默认填充字符为空格。
center(self, width, fillchar=' ', /)
width -- 指定字符串长度。
fillchar -- 填充字符,默认为空格。
str1 = 'sentence'
str2 = 'word'
print(str1.center(20))
print(str2.center(20))
"""
运行结果:sentence word
"""
设置填充字符:
str1 = 'sentence'
str2 = 'word'
print(str1.rjust(20,'-'))
print(str2.rjust(20,'-'))
print(str1.ljust(20,'*'))
print(str2.ljust(20,'*'))
print(str1.center(20,'-'))
print(str2.center(20,'-'))
"""
运行结果:
------------sentence
----------------word
sentence************
word****************
------sentence------
--------word--------
"""