Python3 split()方法
描述
split() 通過指定分隔符號對字串進行切片,如果第二個參數 num 有指定值,則分割為 num+1 個子字串。
語法
split() 方法語法:
str.split(str="", num=string.count(str))
參數
- str -- 分隔符號,默認為所有的空字元,包括空格、換行(\n)、跳位字元(\t)等。
- num -- 分割次數。默認為 -1, 即分隔所有。
返回值
返回分割後的字串列表。
實例
以下實例展示了 split() 函數的使用方法:
實例(Python 3.0+)
#!/usr/bin/python3
str = "this is string example....wow!!!"
print (str.split( )) # 以空格為分隔符號
print (str.split('i',1)) # 以 i 為分隔符號
print (str.split('w')) # 以 w 為分隔符號
以上實例輸出結果如下:
['this', 'is', 'string', 'example....wow!!!'] ['th', 's is string example....wow!!!'] ['this is string example....', 'o', '!!!']
以下實例以 # 號為分隔符號,指定第二個參數為 1,返回兩個參數列表。
實例(Python 3.0+)
#!/usr/bin/python3
txt = "Google#zaixian#Taobao#Facebook"
# 第二個參數為 1,返回兩個參數列表
x = txt.split("#", 1)
print(x)
以上實例輸出結果如下:
['Google', 'zaixian#Taobao#Facebook']