Python split()方法
- 在工作中,我們會遇到很多數據處理的問題,量多且雜的時候就需要用到編程來幫我們節省時間
- 話不多說,直接上代碼
語法
str.split(str="", num=string.count(str)).
參數
- str -- 分隔符,默認為所有的空字符,包括空格、換行(\n)、制表符(\t)等。
- num -- 分割次數。默認為 -1, 即分隔所有。
例子1:
以下實例以 # 號為分隔符,指定第二個參數為 1,返回兩個參數列表。
#!/usr/bin/python # -*- coding: UTF-8 -*- txt = "Google#Runoob#Taobao#Facebook" # 第二個參數為 1,返回兩個參數列表 x = txt.split("#", 1) print x
以上實例輸出結果如下:
['Google', 'Runoob#Taobao#Facebook']
例子2:
實例(Python 2.0+) #!/usr/bin/python # -*- coding: UTF-8 -*- str = "Line1-abcdef \nLine2-abc \nLine4-abcd"; print str.split( ); # 以空格為分隔符,包含 \n print str.split(' ', 1 ); # 以空格為分隔符,分隔成兩個
以上實例輸出結果如下:
['Line1-abcdef', 'Line2-abc', 'Line4-abcd'] ['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
實際應用
只有熟悉語法才能做到活學活用!下面例子是實現只保存中間的網址,去掉'https://'+'/'
a = ''' https://xxx.eye4.cn/ https://xxxx.eye4.cn/ https://xxxxxx.eye4.cn/ https://xxx.eye4.cn/ ''' array = a.split('\n') # 字符串轉換為array數組 # print(array) for obj in array: if obj != "": # 去掉空格 tempArray = obj.split('/') # 去掉/ # print(tempArray) #輸出數組 url = tempArray[2] # 提取第二位數組元素 print(url)
實現的結果為:
xxx.eye4.cn
xxxx.eye4.cn
xxxxxx.eye4.cn
xxx.eye4.cn