python join 和 split方法简单的说是:join用来连接字符串,split恰好相反,拆分字符串的。
.join()
join将 容器对象 拆分并以指定的字符将列表内的元素(element)连接起来,返回字符串(注:容器对象内的元素须为字符类型)
1
2
3
4
|
>>> a
=
[
'no'
,
'pain'
,
'no'
,
'gain'
]
>>>
'_ '
.join(a)
'no_pain_no_gain'
>>>
|
>>> a = ['no','pain','no','gain'] >>> '_ '.join(a) 'no_pain_no_gain' >>>
注:容器对象内的元素须为字符类型
1
2
3
4
5
6
7
|
>>> b
=
[
'I'
,
'am'
,
'no'
,
1
]
>>>
'_'
.join(b)
Traceback (most recent call last):
File
"
, line
1
,
in
'_'
.join(b)
TypeError: sequence item
3
: expected string,
int
found
>>>
|
>>> b = ['I','am','no',1] >>> '_'.join(b) Traceback (most recent call last): File "", line 1, in '_'.join(b) TypeError: sequence item 3: expected string, int found >>>
dict是以Key值作连接
1
2
3
4
|
>>> L
=
{
'p'
:
'P'
,
'y'
:
'Y'
,
't'
:
'T'
,
'h'
:
'H'
,
'o'
:
'O'
,
'n'
:
'N'
}
>>>
'_'
.join(L)
'h_o_n_p_t_y'
#dict 的无序性,使元素随机连接。set 同理
>>>
|
>>> 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
>>> 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'
]
>>>
|
>>> 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)返回的结果是一致的
下面通过一个示例给大家讲下python join 和 split使用方法
1.join用法示例
1
2
3
4
5
6
7
8
9
10
|
>>>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'
|
>>>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用法示例
1
2
3
4
5
6
7
8
9
10
11
12
13
|
>>> 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 = '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("..")