在Python中,我们经常会遇到需要对字符串进行对齐的情况,比如左对齐、右对齐或者居中对齐。这在处理文本输出、日志格式化等场景中非常有用。
方案一:使用 str.ljust()、str.rjust()、str.center() 方法进行对齐
三个方法用法类似,基本格式如下:
string.ljust(width[, fillchar])
- string:表示要进行填充的字符串;
- width:表示包括 S 本身长度在内,字符串要占的总长度;
- fillchar:作为可选参数,用来指定填充字符串时所用的字符,默认情况使用空格。
str = 'python'
print(str.ljust(10, '*'))
# python****
方案二:使用 format() 方法,传递类似 '<20'、'>20'、'^20' 参数
- '<20':左对齐
- '>20': 右对齐
- '^20':居中对齐
str = 'python'
print(format(str, '*^10'))
# **python**
其中,* 代表填充内容,^ 代表居中对齐,10代表填充长度。
num = 128
print(format(num, '10'))
print(format(num, '+10'))
print(format(num, '=+10'))
print(format(num, '0=+10'))
# 输出如下:
# 128
# +128
# + 128
# +000000128
还可以填充数字,做格式化展示。其中,+ 代表输出符号,不论正负,= 代表符号居左,0代表填充0。这是数字对齐的操作办法。