Python - split

Python - split

Built-in Types - 內置類型
https://docs.python.org/3/library/stdtypes.html
https://docs.python.org/zh-cn/3/library/stdtypes.html

1. str.split(sep=None, maxsplit=-1)

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).
返回一個由字符串內單詞組成的列表,使用 sep 作爲分隔字符串。如果給出了 maxsplit,則最多進行 maxsplit 次拆分 (因此,列表最多會有 maxsplit+1 個元素)。如果 maxsplit 未指定或爲 -1,則不限制拆分次數 (進行所有可能的拆分)。

If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns [''].
如果給出了 sep,則連續的分隔符不會被組合在一起而是被視爲分隔空字符串 (例如 '1,,2'.split(',') 將返回 ['1', '', '2'])。sep 參數可能由多個字符組成 (例如 '1<>2<>3'.split('<>') 將返回 ['1', '2', '3'])。使用指定的分隔符拆分空字符串將返回 ['']

>>> '1,2,3'.split(',')
['1', '2', '3']
>>> '1,2,3'.split(',', maxsplit=1)
['1', '2,3']
>>> '1,2,,3,'.split(',')
['1', '2', '', '3', '']

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].
如果 sep 未指定或爲 None,則會應用另一種拆分算法:連續的空格會被視爲單個分隔符,其結果將不包含開頭或末尾的空字符串,如果字符串包含前綴或後綴空格的話。因此,使用 None 拆分空字符串或僅包含空格的字符串將返回 []

>>> '1 2 3'.split()
['1', '2', '3']
>>> '1 2 3'.split(maxsplit=1)
['1', '2 3']
>>> '   1   2   3   '.split()
['1', '2', '3']
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章