新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

Python中split()函数的使用方法-创新互联

这篇文章将为大家详细讲解有关Python中split()函数的使用方法,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

公司主营业务:成都网站制作、网站建设、移动网站开发等业务。帮助企业客户真正实现互联网宣传,提高企业的竞争能力。成都创新互联公司是一支青春激扬、勤奋敬业、活力青春激扬、勤奋敬业、活力澎湃、和谐高效的团队。公司秉承以“开放、自由、严谨、自律”为核心的企业文化,感谢他们对我们的高要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。成都创新互联公司推出丹江口免费做网站回馈大家。

在Python中,split() 方法可以实现将一个字符串按照指定的分隔符切分成多个子串,这些子串会被保存到列表中(不包含分隔符),作为方法的返回值反馈回来。

split函数用法

split(sep=None, maxsplit=-1)

参数

sep – 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。

maxsplit – 分割次数。默认为 -1, 即分隔所有。

实例:

// 例子

String = 'Hello world! Nice to meet you'

String.split()
['Hello', 'world!', 'Nice', 'to', 'meet', 'you']

String.split(' ', 3)
['Hello', 'world!', 'Nice', 'to meet you']

String1, String2 = String.split(' ', 1) 
// 也可以将字符串分割后返回给对应的n个目标,但是要注意字符串开头是否存在分隔符,若存在会分割出一个空字符串
String1 = 'Hello'
String2 = 'world! Nice to meet you'

String.split('!')
// 选择其他分隔符
['Hello world', ' Nice to meet you']

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

上图为Pycharm文档

def my_split(string, sep, maxsplit):
    ret = []
    len_sep = len(sep)
    if maxsplit == -1:
        maxsplit = len(string) + 2
    for _ in range(maxsplit):
        index = string.find(sep)
        if index == -1:
            ret.append(string)
            return ret
        else:
            ret.append(string[:index])
            string = string[index + len_sep:]
    ret.append(string)
    return ret


if __name__ == "__main__":
    print(my_split("abcded", "cd", -1))
    print(my_split('Hello World! Nice to meet you', ' ', 3))

关于“Python中split()函数的使用方法”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。


本文题目:Python中split()函数的使用方法-创新互联
本文URL:http://www.wjwzjz.com/article/diiijo.html
在线咨询
服务热线
服务热线:028-86922220
TOP