Python split()函数的用法
描述
split()通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则仅分隔 num+1 个子字符串
语法
split()方法语法:
str.split(str="", num=string.count(str))
参数
- str -- 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
- num -- 分割次数。默认为 -1, 即分隔所有。
返回值
返回分割后的字符串列表。
实例(Python 3.0+)
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', '!!!']
split()截取后的字符串可以看做一个列表,能通过下标直接找到对应的段
#!/usr/bin/python3
url = "http://www.baidu.com/python/image/123456.jpg"
#以“/” 进行分隔
path =url.split("/")[0]
print(path)
path =url.split("/")[1]
print(path)
path =url.split("/")[2]
print(path)
path =url.split("/")[3]
print(path)
path =url.split("/")[4]
print(path)
path =url.split("/")[5]
print(path)
path =url.split("/")[-1]
print(path)
path =url.split("/")[-2]
print(path)
path =url.split("/")[-3]
print(path)
输出后的结果为url被切割后的几个部分,按下标依次递增,负数则相反,这一点在网页爬虫中较为实用
http:
www.baidu.com
python
image
123456.jpg
123456.jpg
image
python