Python 的 str.split(~) 方法根據指定的分隔符拆分字符串,並返回包含分隔項的列表。
參數
1.sep | string | optional
用於分割字符串的分隔符。默認情況下' '(單個空格)。
2. maxsplit | number | optional
進行的最大分割數。默認情況下-1(即沒有最大值)。
返回值
分隔字符串的列表。
例子
基本用法
分割字符串"a b c":
x = "a b c"
x.split()
['a', 'b', 'c']
默認分隔符是' ',因此該字符串被分成三部分兩次。
九月參數
使用分隔符 "," 分割字符串 "a,b,c" :
y = "a,b,c"
y.split(",")
['a', 'b', 'c']
該字符串在 "a,b,c" 中每次出現 "," 時被拆分。
如果字符串中不存在提供的分隔符",":
z = "abc"
z.split(",")
['abc']
返回包含原始字符串的列表。
最大分割參數
要使用 "," 分隔符和 1 的 maxsplit 值拆分 "a,b,c":
w = "a,b,c"
w.split(",", 1)
['a', 'b,c']
對於 1 的 maxsplit 值,盡管在原始字符串中出現了兩次 ",",但拆分僅發生一次。返回列表的大小始終比提供的 maxsplit 值大 1。
相關用法
- Python String splitlines()用法及代碼示例
- Python String splitlines方法用法及代碼示例
- Python String split()用法及代碼示例
- Python String startswith()用法及代碼示例
- Python String strip方法用法及代碼示例
- Python String strip()用法及代碼示例
- Python String swapcase()用法及代碼示例
- Python String swapcase方法用法及代碼示例
- Python String startswith方法用法及代碼示例
- Python String count方法用法及代碼示例
- Python String isnumeric方法用法及代碼示例
- Python String Center()用法及代碼示例
- Python String zfill方法用法及代碼示例
- Python String rstrip方法用法及代碼示例
- Python String decode()用法及代碼示例
- Python String count()用法及代碼示例
- Python String join()用法及代碼示例
- Python String casefold()用法及代碼示例
- Python String isalnum()用法及代碼示例
- Python String endswith方法用法及代碼示例
- Python String rsplit()用法及代碼示例
- Python String isidentifier()用法及代碼示例
- Python String rjust方法用法及代碼示例
- Python String rpartition()用法及代碼示例
- Python String rpartition方法用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Python String | split method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
