【Python】詳細解說split()分隔字符串並輸出列表的方法,並使用re模塊分割多種符號的字符串

python的spilt()方法可以有效將1個字符串分隔開,並以列表的形式進行輸出。以下是具體的使用方法:

str1 = "Hello world, My name is 王怕怕升職'"
str2 = str1.split() # 以空格爲分隔符,全部分隔
str3 = str1.split(" ", 3) # 以空格爲分隔符,分爲4份
print(str2)
print(str3)

print("---------------------------------")

# 利用re模塊分割含有多種分割符的字符串:
import re
a='Beautiful, is; better + than - ugly'
x= re.split(',|; | \+ | - ',a)
print(x)

print("---------------------------------")

# 分隔後的字符串賦予變量
user, emall = ('[email protected]').split('@')
print('user是:%s, emall是:%s' % (user, emall))

print("---------------------------------")

# 網頁地址解析:
str="http://www.runoob.com/python/att-string-split.html"
print("0:%s"%str.split("/")[-1]) # 分割後的最後1條數據
print("1:%s"%str.split("/")[-2]) # 分割後的倒數第2條數據
print("2:%s"%str.split("/")[-3]) # 分割後的倒數第3條數據
print("5:%s"%str.split("/",-1)) # 默認-1,即分割所有
print("6:%s"%str.split("/",0))  # 分隔1條,即不分割
print("7:%s"%str.split("/",1))  # 分隔2條
運行結果:
['Hello', 'world,', 'My', 'name', 'is', "王怕怕升職'"]
['Hello', 'world,', 'My', "name is 王怕怕升職'"]
---------------------------------
['Beautiful', ' is', 'better', 'than', 'ugly']
---------------------------------
user是:123, emall是:qq.com
---------------------------------
0:att-string-split.html
1:python
2:www.runoob.com
5:['http:', '', 'www.runoob.com', 'python', 'att-string-split.html']
6:['http://www.runoob.com/python/att-string-split.html']
7:['http:', '/www.runoob.com/python/att-string-split.html']

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章