1. 程式人生 > >split("/")[-1] 和 split("/",-1)的區別

split("/")[-1] 和 split("/",-1)的區別

#coding=utf-8

str="http://www.runoob.com/python/att-string-split.html"
print("0:%s"%str.split("/")[-1])
print("1:%s"%str.split("/")[-2])
print("2:%s"%str.split("/")[-3])
print("3:%s"%str.split("/")[-4])
print("4:%s"%str.split("/")[-5])

print("5:%s"%str.split("/",-1))
print("6:%s"%str.split("/",0))
print("7:%s"%str.split("/",1))
print("8:%s"%str.split("/",2))
print("9:%s"%str.split("/",3))
print("10:%s"%str.split("/",4))
print("11:%s"%str.split("/",5))

結果是:

0:att-string-split.html
1:python
2:www.runoob.com
3:
4:http:
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']
8:['http:', '', 'www.runoob.com/python/att-string-split.html']
9:['http:', '', 'www.runoob.com', 'python/att-string-split.html']
10:['http:', '', 'www.runoob.com', 'python', 'att-string-split.html']
11:['http:', '', 'www.runoob.com', 'python', 'att-string-split.html']

即: -1  :全切  0 :不切  1:切一刀  (每一塊都保留)

[-1]:將最後一塊切割出來    [-2]:將倒數第二塊切割出來  (只保留切出來的一塊)