关于python:3种python字符串填充方法

16次阅读

共计 681 个字符,预计需要花费 2 分钟才能阅读完成。

一、获取字符串长度

先看看 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
正文完
 0