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

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

python 搞代码 3年前 (2022-02-20) 10次浏览 已收录 0个评论

字符串中有很多能够应用的函数,本章来解说一下字符串的宰割和合并,首先是宰割字符串,应用到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

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:关于python:python字符串分割和合并split函数-join函数
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

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

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

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