Python split 函式例項用法講解

2022-10-04 13:21:23 字數 1769 閱讀 4151

在pythonwww.cppcns.com中,split() 方法可以實現將乙個字串按照指定的分隔符切分成多個子串,這些子串會被儲存到列表中(不包含分隔符),作為方法的返回值反饋回來。

split(sep=none, maxsplit=-1)

引數sep – 分隔符,預設為所有的空字元,包括空格、換行(\n)、製表符(\t)等。程式設計客棧

maxsplit – 分割次數。預設為 -1, 即分隔所有。

例項:// 例子

string = 'hello world! nice to meet you'

string.split()

['hello', 'world!', 'nice', 'to'www.cppcns.com, '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']

def split(self, *args, **kwargs): # real signature unknown

"""return a list of the words in the string, using sep as the delimiter string.

septhe 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 =

lenwww.cppcns.com_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 函式預設引數

字串的分割一向是我們處理一些資料的常用方法,下面我們看看如下解析 函式宣告 def split self,sep none,maxsplit none str i am a boy.當不給split函式傳遞任何引數時,分隔符sep會採用任意形式的空白字元 空格 tab 換行 回車以及formfeed...

Python split 函式的用法理解

url path url.split 1 print path 輸出結果為 image01.jpg split 拆分字串,通過指定分隔符對字串進行切片,並返回分割後的字串列表 list 語法 str.split str num string.count str n 引數說明 str 表示為分隔符,預...

Python split 函式用法及簡單實現

split sep none,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...