当前位置:   article > 正文

Python 字符串对齐方法(ljust()、rjust()和center())_ljust(width,[fillchar])

ljust(width,[fillchar])


Python 字符串对齐方法

Python str 提供了 3 种可用来进行文本对齐的方法,分别是 ljust()、rjust() 和 center() 方法,本节就来一一介绍它们的用法。

Python ljust()方法

ljust() 方法的功能是向指定字符串的右侧填充指定字符,从而达到左对齐文本的目的。

ljust() 方法的基本格式如下:

S.ljust(width[, fillchar])
  • 1

其中各个参数的含义如下:

  • S:表示要进行填充的字符串;
  • width:表示包括 S 本身长度在内,字符串要占的总长度;
  • fillchar:作为可选参数,用来指定填充字符串时所用的字符,默认情况使用空格。

【例 1】

S = 'https://editor.csdn.net/md?not_checkout=1&articleId=125648923'
addr = 'https://editor.csdn.net/'
print(S.ljust(35))
print(addr.ljust(35))
  • 1
  • 2
  • 3
  • 4

输出结果为:

https://editor.csdn.net/md?not_checkout=1&articleId=125648923
https://editor.csdn.net/

注意,该输出结果中除了明显可见的网址字符串外,其后还有空格字符存在,每行一共 35 个字符长度。

【例 2】

S = 'https://editor.csdn.net/md?not_checkout=1&articleId=125648923'
addr = 'https://editor.csdn.net/'
print(S.ljust(35,'-'))
print(addr.ljust(35,'-'))
  • 1
  • 2
  • 3
  • 4

输出结果为:

https://editor.csdn.net/md?not_checkout=1&articleId=125648923-----
https://editor.csdn.net/t-------------

此程序和例 1 的唯一区别是,填充字符从空格改为‘-’。

Python rjust()方法

rjust() 和 ljust() 方法类似,唯一的不同在于,rjust() 方法是向字符串的左侧填充指定字符,从而达到右对齐文本的目的。

rjust() 方法的基本格式如下:

S.rjust(width[, fillchar])
  • 1

其中各个参数的含义和 ljust() 完全相同,所以这里不再重复描述。

【例 3】

S = 'https://editor.csdn.net/md?not_checkout=1&articleId=125648923'
addr = 'https://editor.csdn.net/'
print(S.rjust(35))
print(addr.rjust(35))
  • 1
  • 2
  • 3
  • 4

输出结果为:

 https://editor.csdn.net/md?not_checkout=1&articleId=125648923
         https://editor.csdn.net/         
  • 1
  • 2

可以看到,每行字符串都占用 35 个字节的位置,实现了整体的右对齐效果。

【例 4】

S = 'https://editor.csdn.net/md?not_checkout=1&articleId=125648923'
addr = 'https://editor.csdn.net/'
print(S.rjust(35,'-'))
print(addr.rjust(35,'-'))
  • 1
  • 2
  • 3
  • 4

输出结果为:

-----https://editor.csdn.net/md?not_checkout=1&articleId=125648923
-------------https://editor.csdn.net/

Python center()方法

center() 字符串方法与 ljust() 和 rjust() 的用法类似,但它让文本居中,而不是左对齐或右对齐。

center() 方法的基本格式如下:

S.center(width[, fillchar])
  • 1

其中各个参数的含义和 ljust()、rjust() 方法相同。

【例 5】

S = 'https://editor.csdn.net/md?not_checkout=1&articleId=125648923'
addr = 'https://editor.csdn.net/'
print(S.center(35,))
print(addr.center(35,))
  • 1
  • 2
  • 3
  • 4

输出结果为:

   https://editor.csdn.net/md?not_checkout=1&articleId=125648923
       https://editor.csdn.net/    
  • 1
  • 2

【例 6】

S = 'https://editor.csdn.net/md?not_checkout=1&articleId=125648923'
addr = 'https://editor.csdn.net/'
print(S.center(35,'-'))
print(addr.center(35,'-'))
  • 1
  • 2
  • 3
  • 4

输出结果为:

—https://editor.csdn.net/md?not_checkout=1&articleId=125648923–
-------https://editor.csdn.net/------

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/294606
推荐阅读
相关标签
  

闽ICP备14008679号