首页 python基础教程 Python字符串长度获取len()和填充(ljust()、rjust()、center())
pay pay
教程目录

Python字符串长度获取len()和填充(ljust()、rjust()、center())

日期: 二月 13, 2023, 5:17 a.m.
栏目: python基础教程
阅读: 1157
作者: Python自学网-村长

摘要: 获取和填充Python字符串长度

一、获取字符串长度

先看看len()函数的构造

def len(*args, **kwargs): # real signature unknown
    """ Return the number of items in a container. """
    pass

看来函数中的传参都不受限制,我们来一段代码试试

web = 'wakey.com.cn'
print(len(web))

返回结果是:12 

二、字符串填充

1. ljust(width, fillchar),width表示填充后字符串总长度,fillchar表示需要填充的字符。

name = 'python自学网'
res = name.ljust(50, '*')
print(res)
print(len(res))

返回结果:
python自学网*****************************************
50

2. rjust(width, fillchar)方法,和ljust()方法类似,唯一的不同就是把填充的字符串填充在原有字符串前面。

name = 'python自学网'
res = name.rjust(50, '*')
print(res)
print(len(res))

返回结果是:
*****************************************python自学网
50

3. center(width, fillchar)方法,是把原有字符串放在填充字符串中间,如果是奇数,先填充在后面。

name = 'python自学网'
res = name.center(12, '*')
print(res)
print(len(res))

返回结果:
*python自学网**
12

 

 

部分文字内容为【Python自学网】原创作品,转载请注明出处!视频内容已申请版权,切勿转载!
回顶部