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

在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('!')
//选择其他分隔符
['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()函数用法及简单实现,希望能帮助到你哦~

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。