python字符串对齐的三种方法

Python (177) 2023-06-25 04:35:51

说明

1、ljust()用于向指定字符串的右侧填充指定字符。

从而达到左对齐文本的目的。

2、rjust()方法是在字符串左侧填充指定字符。
从而达到右对齐文本的目的。

3、center()方法用于使文本居中,而非左对齐或右对齐。

实例

纯文本
复制到剪贴板
在新窗口中打开代码
EnlighterJS 3 Syntax Highlighter
str1='https://feige.blog.csdn.net/'
str2='https://www.baidu.com/'
print("通过-实现左对齐",str1.ljust(30,'-'))
print("通过-实现左对齐",str2.ljust(30,'-'))
print("通过-实现右对齐",str1.rjust(30,'-'))
print("通过-实现右对齐",str2.rjust(30,'-'))
print("通过-实现居中对齐",str1.center(30,'-'))
print("通过-实现居中对齐",str2.center(30,'-'))
str1='https://feige.blog.csdn.net/' str2='https://www.baidu.com/' print("通过-实现左对齐",str1.ljust(30,'-')) print("通过-实现左对齐",str2.ljust(30,'-')) print("通过-实现右对齐",str1.rjust(30,'-')) print("通过-实现右对齐",str2.rjust(30,'-')) print("通过-实现居中对齐",str1.center(30,'-')) print("通过-实现居中对齐",str2.center(30,'-'))
str1='https://feige.blog.csdn.net/'
str2='https://www.baidu.com/'
print("通过-实现左对齐",str1.ljust(30,'-'))
print("通过-实现左对齐",str2.ljust(30,'-'))
print("通过-实现右对齐",str1.rjust(30,'-'))
print("通过-实现右对齐",str2.rjust(30,'-'))
print("通过-实现居中对齐",str1.center(30,'-'))
print("通过-实现居中对齐",str2.center(30,'-'))

以上就是python字符串对齐的三种方法,希望对大家有所帮助。

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

THE END

发表回复