Python中join 和 split详解
python join 和 split方法简单的说是:join用来连接字符串,split恰好相反,拆分字符串的。
.join()
join将 容器对象 拆分并以指定的字符将列表内的元素(element)连接起来,返回字符串(注:容器对象内的元素须为字符类型)
>>> a = ["no","pain","no","gain"]
>>> "_ ".join(a)
"no_pain_no_gain"
>>>
dict是以Key值作连接
>>> L = {"p":"P","y":"Y","t":"T","h":"H","o":"O","n":"N"}
>>> "_".join(L)
"h_o_n_p_t_y" #dict 的无序性,使元素随机连接。set 同理
>>>
.split()
与join相反,split以指定的字符将字符串分割为单个元素(字符类型)并加入list中,返回一个List
>>> a = "no_pian_no_gain"
>>> a.split("_")
["no", "pian", "no", "gain"]
>>>
split是可以设定切割多少个字符的
#Python学习交流群:579817333
>>> a = "no_pian_no_gain"
>>> a.split("_",2)
["no", "pian", "no_gain"]
>>> a.split("_",1)
["no", "pian_no_gain"]
>>> a.split("_",0)
["no_pian_no_gain"]
>>> a.split("_",-1)
["no", "pian", "no", "gain"]
>>>
可见split("_")
与split("_",-1)
返回的结果是一致的
下面通过一个示例给大家讲下python join 和 split使用方法
1.join用法示例
>>>li = ["my","name","is","bob"]
>>>" ".join(li)
"my name is bob"
>>>"_".join(li)
"my_name_is_bob"
>>> s = ["my","name","is","bob"]
>>> " ".join(s)
"my name is bob"
>>> "..".join(s)
"my..name..is..bob"
2.split用法示例
>>> b = "my..name..is..bob"
>>> b.split()
["my..name..is..bob"]
>>> b.split("..")
["my", "name", "is", "bob"]
>>> b.split("..",0)
["my..name..is..bob"]
>>> b.split("..",1)
["my", "name..is..bob"]
>>> b.split("..",2)
["my", "name", "is..bob"]
>>> b.split("..",-1)
["my", "name", "is", "bob"]
可以看出 b.split("..",-1)
等价于b.split("..")