描述
split()通過指定分隔符對字符串進行切片,如果參數 num 有指定值,則僅分隔 num+1 個子字符串
語法
split()方法語法:
str.split(str="", num=string.count(str))
參數
- sep -- 可選參數,指定的分隔符,默認為所有的空字符,包括空格、換行(\n)、制表符(\t)等。
- count -- 可選參數,分割次數,默認為分隔符在字符串中出現的總次數。
返回值
返回分割后的字符串列表。
實例
以下實例展示了split()函數的使用方法:
str = "this is string example....wow!!!" print(str.split()) print(str.split("i", 1)) print(str.split("w")) # 結果為 # ['this', 'is', 'string', 'example....wow!!!'] # ['th', 's is string example....wow!!!'] # ['this is string example....', 'o', '!!!']
以下實例以 # 號為分隔符,指定第二個參數為 2,返回三個參數列表。
tst = "Google#Runoob#Taobao#Facebook" print(tst.split("#", 2)) # 結果為 # ['Google', 'Runoob', 'Taobao#Facebook']