Python-split()函数用法及简单实现

split函数用法

split(sep=None, maxsplit=-1)

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

[if !supportLists]· [endif]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))


注册 - 代码课堂-专注在线编程学习,零基础编程入门的教程网站!

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容