Python-split()函數(shù)實例用法講解
在Python中,split() 方法可以實現(xiàn)將一個字符串按照指定的分隔符切分成多個子串,這些子串會被保存到列表中(不包含分隔符),作為方法的返回值反饋回來。
split函數(shù)用法
split(sep=None, maxsplit=-1)
參數(shù)
sep – 分隔符,默認(rèn)為所有的空字符,包括空格、換行(\n)、制表符(\t)等。
maxsplit – 分割次數(shù)。默認(rèn)為 -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) // 也可以將字符串分割后返回給對應(yīng)的n個目標(biāo),但是要注意字符串開頭是否存在分隔符,若存在會分割出一個空字符串 String1 = 'Hello' String2 = 'world! Nice to meet you' String.split('!') // 選擇其他分隔符 ['Hello world', ' Nice to meet you']
split函數(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 ret if __name__ == "__main__": print(my_split("abcded", "cd", -1)) print(my_split('Hello World! Nice to meet you', ' ', 3))
到此這篇關(guān)于Python-split()函數(shù)實例用法講解的文章就介紹到這了,更多相關(guān)Python-split()函數(shù)用法及簡單實現(xiàn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python3.6.3安裝圖文教程 TensorFlow安裝配置方法
這篇文章主要為大家詳細(xì)介紹了python3.6.3及TensorFlow安裝配置方法圖文教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-09-09Python 多線程,threading模塊,創(chuàng)建子線程的兩種方式示例
這篇文章主要介紹了Python 多線程,threading模塊,創(chuàng)建子線程的兩種方式,結(jié)合實例形式分析了Python線程的原理與創(chuàng)建子線程的相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2019-09-09講解Python的Scrapy爬蟲框架使用代理進行采集的方法
這篇文章主要介紹了講解Python的Scrapy爬蟲框架使用代理進行采集的方法,并介紹了隨機使用預(yù)先設(shè)好的user-agent來進行爬取的用法,需要的朋友可以參考下2016-02-02Python中conda虛擬環(huán)境創(chuàng)建及使用小結(jié)
本文主要介紹了Python中conda虛擬環(huán)境創(chuàng)建及使用小結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-03-03Python實現(xiàn)基于PIL和tesseract的驗證碼識別功能示例
這篇文章主要介紹了Python實現(xiàn)基于PIL和tesseract的驗證碼識別功能,結(jié)合實例形式分析了Python使用PIL與tesseract進行驗證碼識別操作的具體技巧與相關(guān)注意事項,需要的朋友可以參考下2018-07-07