Python split 函式用法及簡單實現

2021-10-12 05:21:33 字數 2000 閱讀 2508

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'

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

len_sep =

len(sep)

if maxsplit ==-1

: maxsplit =

len(string)+2

for _ in

range

(maxsplit)

: index = string.

find

(sep)

if index ==-1

: ret.

(string)

return ret

else

: ret.

(string[

:index]

) string = string[index + len_sep:

] ret.

(string)

return ret

if __name__ ==

"__main__"

:print

(my_split

("abcded"

,"cd",-

1))print

(my_split

('hello world! nice to meet you'

,' ',3

))

Python split 函式例項用法講解

在pythonwww.cppcns.com中,split 方法可以實現將乙個字串按照指定的分隔符切分成多個子串,這些子串會被儲存到列表中 不包含分隔符 作為方法的返回值反饋回來。split sep none,maxsplit 1 引數sep 分隔符,預設為所有的空字元,包括空格 換行 n 製表符 t...

python split用法大全

python中有split 和os.path.split 兩個函式,具體作用如下 split 拆分字串。通過指定分隔符對字串進行切片,並返回分割後的字串列表 list os.path.split 按照路徑將檔名和路徑分割開 一 函式說明 1 split 函式 語法 str.split str num...

Python split 函式的用法理解

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