前言
- Python中split是一个内置函数,用来对字符串进行分割,分割后的字符串以列表形式返回,该函数的语法是“str.split(str=“”,num=string.count(str))”
一、split()函数使用方法
split()中如果没有参数,函数默认以空格,tab空格符,换行符等作为分割条件
String_0 = "www.com aaa bbb QJ6252630247.jpg"
String_1 = "www.com\taaa\tbbb\tQJ6252630247.jpg"
String_2 = "www.com\naaa\nbbb\nQJ6252630247.jpg"
a = String_0.split()
b = String_1.split()
c = String_2.split()
print(a)
print(b)
print(c)
结果:
['www.com', 'aaa', 'bbb', 'QJ6252630247.jpg']
['www.com', 'aaa', 'bbb', 'QJ6252630247.jpg']
['www.com', 'aaa', 'bbb', 'QJ6252630247.jpg']
split("/")中有参数时,会以参数作为分割条件,把字符串进行分割,得到的每个分割段作为列表的元素返回
String_0 = "www.com/aaa/bbb/QJ6252630247.jpg"
String_1 = "www.com-aaa-bbb-QJ6252630247.jpg"
String_2 = "www.com:aaa:bbb:QJ6252630247.jpg"
a = String_0.split("/")
b = String_1.split("-")
c = String_2.split(":")
print(a)
print(b)
print(c)
结果:
['www.com', 'aaa', 'bbb', 'QJ6252630247.jpg']
['www.com', 'aaa', 'bbb', 'QJ6252630247.jpg']
['www.com', 'aaa', 'bbb', 'QJ6252630247.jpg']
第二个参数表示分割几次
String_0 = "www:com:aaa:bbb:QJ6252630247.jpg"
a = String_0.split(":", 1)
b = String_0.split(":", 2)
c = String_0.split(":", 3)
d = String_0.split(":", 4)
print(a)
print(b)
print(c)
print(d)
结果:
['www', 'com:aaa:bbb:QJ6252630247.jpg']
['www', 'com', 'aaa:bbb:QJ6252630247.jpg']
['www', 'com', 'aaa', 'bbb:QJ6252630247.jpg']
['www', 'com', 'aaa', 'bbb', 'QJ6252630247.jpg']
String_0 = "www.com/aaa/bbb/QJ6252630247.jpg"
a = String_0.split("/")[-1]
print(a)
结果:
QJ6252630247.jpg