str.rjust|ljust|center(width[, fillchar])
1、 rjust() 返回一个原字符串右对齐,ljust() 返回一个原字符串左对齐,center() 返回一个原字符串居中;
a = 'hello world'
def get_str(strs,width,fillchar=' '):
global a
print(eval("a.{}({},'{}')".format(strs,width,fillchar)))
get_str('rjust', 22)
get_str('ljust', 22, '*')
get_str('center', 22, '*')
out:
hello world
hello world***********
*****hello world******
2、默认填充字符为空格填充至长度 width 的新字符串,如果指定的长度小于原字符串的长度则返回原字符串。
get_str('rjust', 10)
get_str('ljust', 10, '*')
get_str('center', 10, '*')
out:
hello world
hello world
hello world
3、当center()无法使左右字符数相等时候,字符串字符数为偶数时左侧字符会比右侧多 1,字符串字符数为奇数时左侧字符会比右侧少 1
get_str('center', 14, '*')
a = 'helloworld'
get_str('center', 13, '*')
out:
*hello world**
**helloworld*
本文介绍了Python中字符串的rjust、ljust和center方法,用于实现字符串的右对齐、左对齐和居中对齐。示例展示了如何使用这些方法填充指定宽度的字符串,并演示了不同填充字符的效果。同时,还提到了当使用center方法时,字符串长度为偶数和奇数时两侧填充字符的数量差异。
1586

被折叠的 条评论
为什么被折叠?



