• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python字符串对齐方法使用(ljust()、rjust()和center())

python 搞代码 4年前 (2022-01-09) 21次浏览 已收录 0个评论

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

Python ljust()方法

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

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

S.ljust(width[, fillchar])

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

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

【例 1】

S = '//www.gaodaima.com/python/'
addr = '//www.gaodaima.com'
print(S.ljust(35))
print(addr.ljust(35))

输出结果为:

//www.gaodaima.com/python/   
//www.gaodaima.com           

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

【例 2】

S = '//www.gaodaima.com/python/'
addr = '//www.gaodaima.com'
print(S.ljust(35,'-'))
print(addr.ljust(35,'-'))

输出结果为:

//www.gaodaima.com/python/—–
//www.gaodaima.com————-

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

Python rjust()方法

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

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

S.rjust(width[, fillchar])

其中各个参数的含义和来源gaodai#ma#com搞@代~码$网 ljust() 完全相同,所以这里不再重复描述。

【例 3】

S = '//www.gaodaima.com/python/'
addr = '//www.gaodaima.com'
print(S.rjust(35))
print(addr.rjust(35))

输出结果为:
     //www.gaodaima.com/python/
             //www.gaodaima.com         

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

【例 4】

S = '//www.gaodaima.com/python/'
addr = '//www.gaodaima.com'
print(S.rjust(35,'-'))
print(addr.rjust(35,'-'))

输出结果为:
—–//www.gaodaima.com/python/
————-//www.gaodaima.com

Python center()方法

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

center() 方法的基本格式如下:
S.center(width[, fillchar])

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

【例 5】

S = '//www.gaodaima.com/python/'
addr = '//www.gaodaima.com'
print(S.center(35,))
print(addr.center(35,))

输出结果为:
   //www.gaodaima.com/python/
       //www.gaodaima.com   

【例 6】

S = '//www.gaodaima.com/python/'
addr = '//www.gaodaima.com'
print(S.center(35,'-'))
print(addr.center(35,'-'))

输出结果为:
—//www.gaodaima.com/python/–
——-//www.gaodaima.com——

到此这篇关于Python字符串对齐方法使用(ljust()、rjust()和center())的文章就介绍到这了,更多相关Python字符串对齐内容请搜索搞代码以前的文章或继续浏览下面的相关文章希望大家以后多多支持搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python字符串对齐方法使用(ljust()、rjust()和center())

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址