在Python中,split() 该方法可以根据指定的分隔符将字符串切割成多个子串,并将其保存在列表中(不包括分隔符)作为方法的返回值反馈。
split函数用法
split(sep=None,maxsplit=-1)
参数
sep – 分隔符,默认为所有空字符,包括空格和换行(\n)、制表符(\t)等。
maxsplit – 分割次数。默认为 -1, 也就是说,把一切分开。
实例:
//例子 String='Helloworld!Nicetomeetyou' String.split() ['Hello','world!','Nice','to','meet','you'] String.split('',3) ['Hello','world!','Nice','tomeetyou'] String1,String2=String.split('',1) //也可以将字符串分割并返回到相应的n个目标,但要注意字符串开头是否有分隔符,如果存在,将划分一个空字符串 String1='Hello' String2='world!Nicetomeetyou' String.split('!Nicetomeetyou' String.split('!') //选择其他分隔符 ['Helloworld','Nicetomeetyou']实现split函数
defsplit(self,*args,**kwargs):#realsignatureunknown """ Returnalistofthewordsinthestring,usingsepasthedelimiterstring. sep Thedelimiteraccordingwhichtosplitthestring. None(thedefaultvalue)meanssplitaccordingtoanywhitespace, anddiscardemptystringsfromtheresult. maxsplit Maximumnumberofsplitstodo. -1(thedefaultvalue)meansnolimit. """ pass
上图为Pycharm文档
defmy_split(string,sep,maxsplit): ret=[] len_sep=len(sep) ifmaxsplit==-1: maxsplit=len(string)+2 for_inrange(maxsplit): index=string.find(sep) ifindex==-1: ret.append(string) returnret else: ret.append(string[:index]) string=string[index+len_sep:] ret.append(string) returnret if__name__=="__main__": print(my_split("abcded","cd",-1)) print(my_split('HelloWorld!Nicetomeetyou','',3))
以上是Python-split()函数用法和简单实现,希望对你有所帮助~
(推荐操作系统:windows7系统Python 3.9.1,DELL G3电脑。)