关于python:python字符串分割和合并split函数-join函数

3次阅读

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

字符串中有很多能够应用的函数,本章来解说一下字符串的宰割和合并,首先是宰割字符串,应用到 split() 函数,合并字符串的时候应用的 join() 函数。上面咱们就来一一解说一下。

一、字符串宰割

应用 split() 函数来宰割字符串的时候,先看看构造方法。
def split(self, args, *kwargs): # real signature unknown

"""
Return a list of the words in the string, using sep as the delimiter string.

  sep
    The delimiter according which to split the string.
    None (the default value) means split according to any whitespace,
    and discard empty strings from the result.
  maxsplit
    Maximum number of splits to do.
    -1 (the default value) means no limit.
"""
pass

这外面能够传很多类型参数,然而咱们次要讲两个 str.split(sep,maxsplit),sep 是宰割符,指的是依照什么字符来宰割字符串,maxsplit 示意把字符串宰割成几段。上面来看看代码。

website = 'http://www.wakey.com.cn/'
print(website.split('.', -1)) 
 # 依照字符串中的. 来宰割,不限次数
print(website.split('.', 2)) 
 #依照字符串中的. 来宰割,宰割成 3 份
print(website.split('w', 5))  
#依照字符串中的 w 来宰割,宰割成 6 份
返回后果:['http://www', 'wakey', 'com', 'cn/']
['http://www', 'wakey', 'com.cn/']
['http://', '','', '.', 'akey.com.cn/']

二、字符串合并

字符串合并在日后的开发中会常常用到,上面咱们先来看看字符串合并函数 join() 的结构。

def join(self, ab=None, pq=None, rs=None): # real signature unknown; restored from __doc__
    """
    Concatenate any number of strings.
    
    The string whose method is called is inserted in between each given string.
    The result is returned as a new string.
    
    Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
    """
    pass

看了结构就晓得函数内须要传入可迭代对象,所以咱们先传入一个列表演示一下。

website = '.'
list = ['www', 'wakey', 'com', 'cn']
print('http://' + website.join(list))
返回后果:http://www.wakey.com.cn
正文完
 0