Home > Article > Backend Development > A brief analysis of join and split in Python
The python join and split methods are simply: join is used to connect strings, and split is just the opposite, splitting strings.
.join()
Join splits the container object and connects the elements in the list with the specified characters, and returns a string (note: within the container object The elements must be of character type)
>>> a = ['no','pain','no','gain'] >>> '_ '.join(a) 'no_pain_no_gain' >>>
Note: The elements in the container object must be of character type
>>> 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 is connected by Key value
>>> L = {'p':'P','y':'Y','t':'T','h':'H','o':'O','n':'N'} >>> '_'.join(L) 'h_o_n_p_t_y' #dict 的无序性,使元素随机连接。set 同理 >>>
.split()
In contrast to join, split uses the specified Character splits the string into single elements (character type) and adds them to the list, returning a 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'] >>>
Visible split('_') and split(' _',-1) The returned results are consistent
The following is an example of how to use python join and split
1.Join usage example
>>>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 usage example
>>> 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']
It can be seen that b.split("..",-1 ) is equivalent to b.split("..")
For more articles on join and split in Python, please pay attention to the PHP Chinese website!