1,str.split
官方文档如下:
str.split(sep=None, maxsplit=-1)
Return a list of the words in the string, using sep as the delimiter string.
If maxsplit is given, at most maxsplit splits are done (thus,
the list will have at most maxsplit+1 elements).
If maxsplit is not specified or -1,
then there is no limit on the number of splits (all possible splits are made).
If sep is given, consecutive delimiters are not grouped together and are
deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']).
The sep argument may consist of multiple characters (for example,
'1<>2<>3'.split('<>') returns ['1', '2', '3']).
Splitting an empty string with a specified separator returns ['']
seq
是分隔符,如'_'
,'.'
等。maxsplit是分隔次数,如为1,就从第一个出现分隔符的地方分隔一次,则字符串就变成两串了。
例子如下:
>>> a = 'x_y_z_a_b_c'
>>> a.split(sep='_', maxsplit=1) # 拆一次,分隔符为_
['x', 'y_z_a_b_c']
>>> a.split(sep='_', maxsplit=2) # 拆两次
['x', 'y', 'z_a_b_c']
>>> a.split(sep='_', maxsplit=-1) # 全拆
['x', 'y', 'z', 'a', 'b', 'c']
2,.join
。把字符串用设定的连接符连接起来。例子如下:
>>> a = 'x_y_z_a_b_c'
>>> b = a.split(sep='_', maxsplit=-1)[0:-1] # 全拆之后,取第一至倒数第二的str
['x', 'y', 'z', 'a', 'b']
>>> '_'.join(b) # 用_把str连接起来。
'x.y.z.a.b'
>>> ''.join(b) # 用空白连接起来
'xyzab'