知行编程网知行编程网  2022-09-10 13:30 知行编程网 隐藏边栏  28 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于Python-split()函数用法及简单实现的相关知识,包括python中type函数的作用,以及strncmp函数用法这些编程知识,希望对大家有参考作用。



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()函数的用法和简单实现,希望对大家有所帮助~



(推荐操作系统:windows7系统、Python 3.9.1,DELL G3电脑。)

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享