【100+ python基础入门-15】字符串的分割和合并

字符串中有很多可以使用的函数,本章来讲解一下字符串的分割和合并,首先是分割字符串,使用到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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王子玉博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值