Python-split()函數(shù)實(shí)例用法講解
在Python中,split() 方法可以實(shí)現(xiàn)將一個(gè)字符串按照指定的分隔符切分成多個(gè)子串,這些子串會(huì)被保存到列表中(不包含分隔符),作為方法的返回值反饋回來。
split函數(shù)用法split(sep=None, maxsplit=-1)
參數(shù)
sep ? 分隔符,默認(rèn)為所有的空字符,包括空格、換行(n)、制表符(t)等。
maxsplit ? 分割次數(shù)。默認(rèn)為 -1, 即分隔所有。
實(shí)例:
// 例子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) // 也可以將字符串分割后返回給對(duì)應(yīng)的n個(gè)目標(biāo),但是要注意字符串開頭是否存在分隔符,若存在會(huì)分割出一個(gè)空字符串String1 = ’Hello’String2 = ’world! Nice to meet you’String.split(’!’)// 選擇其他分隔符[’Hello world’, ’ Nice to meet you’]split函數(shù)實(shí)現(xiàn)
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 retif __name__ == '__main__': print(my_split('abcded', 'cd', -1)) print(my_split(’Hello World! Nice to meet you’, ’ ’, 3))
到此這篇關(guān)于Python-split()函數(shù)實(shí)例用法講解的文章就介紹到這了,更多相關(guān)Python-split()函數(shù)用法及簡(jiǎn)單實(shí)現(xiàn)內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. PHP橋接模式Bridge Pattern的優(yōu)點(diǎn)與實(shí)現(xiàn)過程2. asp.net core項(xiàng)目授權(quán)流程詳解3. html中的form不提交(排除)某些input 原創(chuàng)4. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼5. CSS3中Transition屬性詳解以及示例分享6. bootstrap select2 動(dòng)態(tài)從后臺(tái)Ajax動(dòng)態(tài)獲取數(shù)據(jù)的代碼7. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式8. 開發(fā)效率翻倍的Web API使用技巧9. jsp文件下載功能實(shí)現(xiàn)代碼10. ASP常用日期格式化函數(shù) FormatDate()
