python字符串对齐

作者:落知秋 | 创建时间: 2023-05-07
介绍如何用python实现字符串的对齐格式化...
python字符串对齐

使用ljust,rjust,center方法

ljust,rjust,center这三个方法都可以设定对齐长度,填充字符。 直接上测试代码 text="我是字符串"; print(text); print(text.ljust(20)); print(text.rjust(20)); print(text.center(20)); print(text.ljust(20,'/')); print(text.rjust(20,'~')); print(text.center(20,"*"));

上面代码对应的运行结果

使用format方法

format方法同样可以用来对齐字符串  <左对齐   >右对齐   ^中间对齐 text="我是字符串"; print(text); print(format(text,"<20")); print(format(text,">20")); print(format(text,"^20")); print(format(text,"/<20")); print(format(text,"~>20")); print(format(text,"*^20"));

上面代码对应的运行结果,可以看到与ljust,rjust,center都能达到同样的效果

温馨提示

tips:format这个方法非常的强大,它不仅只对字符串起作用,它还可以来格式化数字。具体方法可以查阅相关资料。
点击展开全文

更多推荐