Python--关于 join 和 split
.join()
join将 容器对象 拆分并以指定的字符将列表内的元素(element)连接起来,返回字符串(注:容器对象内的元素须为字符类型)
>>> a = ['no','pain','no','gain']
>>> '_ '.join(a)
'no_pain_no_gain'
>>>
注:容器对象内的元素须为字符类型
>>> b = ['I','am','no',1]
>>> '_'.join(b)
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
'_'.join(b)
TypeError: sequence item 3: expected string, int found
>>>
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是可以设定切割多少个字符的
>>> 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)返回的结果是一致的