加入收藏 | 设为首页 | 会员中心 | 我要投稿 北几岛 (https://www.beijidao.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Python3 如何对字符串进行左、右、居中对齐

发布时间:2021-07-06 06:01:08 所属栏目:大数据 来源: https://blog.csdn.net/yilovex
导读:1. 使用 str 内置方法 In [1]: data = 'hello world!'In [2]: data.ljust(20)Out[2]: 'hello world! 'In [3]: data.rjust(20)Out[3]: ' hello world!'In [4]: data.center(20)Out[4]: ' hello world! ' 2. 使用 print 格式化处理 print 没有内置居中对齐的设

1. 使用 str 内置方法

In [1]: data = 'hello world!'

In [2]: data.ljust(20)
Out[2]: 'hello world!        '

In [3]: data.rjust(20)
Out[3]: '        hello world!'

In [4]: data.center(20)
Out[4]: '    hello world!    '

2. 使用 print 格式化处理

print 没有内置居中对齐的设置,需要我们自己写一个

In [5]: print('%-20s' % data)
'hello world!        '

In [6]: print('%20s' % data)
'        hello world!'

In [7]: print('%s%s' % (' '*((20-len(data))//2),data))
'    hello world!    '

3. 使用 format 方法

In [8]: format(data,'<20')
Out[8]: 'hello world!        '

In [9]: format(data,'>20')
Out[9]: '        hello world!'

In [10]: format(data,'^20')
Out[10]: '    hello world!    '

(编辑:北几岛)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读