python中list index out of range_Python知识精解:str split()方法
生活随笔
收集整理的這篇文章主要介紹了
python中list index out of range_Python知识精解:str split()方法
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
描述
split()函數(shù)是Python字符串函數(shù)。split() 通過(guò)指定分隔符對(duì)字符串進(jìn)行切片。如果指定了整型參數(shù)num,則僅分隔num + 1個(gè)子字符串(即分割num次)。使用split()函數(shù)將字符串分割后,返回的是一個(gè)列表,列表中存儲(chǔ)著分割后的每個(gè)子串。
語(yǔ)法及參數(shù)
str.split(string, num)實(shí)例
1. 所有參數(shù)都省略
s = 'Hello world!' d = s.split() print(d)輸出結(jié)果為:
['Hello', 'world!']2. 僅指定分隔符
s = 'Hello world! I am Python&I am not Java!' d = s.split('&') print(d)輸出結(jié)果為:
['Hello world! I am Python', 'I am not Java!']3. 指定分隔符和分割次數(shù)
s = 'I am Python&I am not Java!&Python is Interesting' d = s.split('&', 1) print(d)輸出結(jié)果為:
['I am Python', 'I am not Java!&Python is Interesting']注意事項(xiàng)
1. 使用split()后,有效分隔符不會(huì)存在于任何子串中。
有效分隔符:待分割的字符串中存在該分隔符,且num參數(shù)有效。
>>> s = "list&index&out&of&range" >>> s_l = s.split("&") >>> s_l.count("&") 0 >>> s_l ['list', 'index', 'out', 'of', 'range']2. 使用空字符串作為分隔符時(shí),Python會(huì)報(bào)錯(cuò)
當(dāng)使用空字符串作為分隔符時(shí),Python會(huì)拋出ValueError。
>>> demo = "a, b, c, d" >>> demo.split("") Traceback (most recent call last):File "<stdin>", line 1, in <module> ValueError: empty separator覺(jué)得有用的同學(xué)可以點(diǎn)下贊同呀~
關(guān)注我,獲得更多技術(shù)知識(shí)~
總結(jié)
以上是生活随笔為你收集整理的python中list index out of range_Python知识精解:str split()方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 罗永浩吐槽苹果抄袭引热议 网友:太敢说
- 下一篇: 苹果M2芯片提升不明显 致使M1版Mac