在抓取網絡數(shù)據(jù)的時候,有時會用正則對結構化的數(shù)據(jù)進行提取,比如 href="https://www.1234.com"等。python的re模塊的findall()函數(shù)會返回一個所有匹配到的內容的列表,在將數(shù)據(jù)存入數(shù)據(jù)庫時,列表數(shù)據(jù)類型是不被允許的,而是需要將其轉換為元組形式。下面看下,str/list/tuple三者之間怎么相互轉換。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
class forDatas: def __init__( self ): pass def str_list_tuple( self ): s = 'abcde12345' print ( 's:' , s, type (s)) # str to list l = list (s) print ( 'l:' , l, type (l)) # str to tuple t = tuple (s) print ( 't:' , t, type (t)) # str轉化為list/tuple,直接進行轉換即可 # 由list/tuple轉換為str,則需要借助join()函數(shù)來實現(xiàn) # list to str s1 = ''.join(l) print ( 's1:' , s1, type (s1)) # tuple to str s2 = ''.join(t) print ( 's2:' , s2, type (s2)) |
str轉化為list/tuple,直接進行轉換即可。而由list/tuple轉換為str,則需要借助join()函數(shù)來實現(xiàn)。join()函數(shù)是這樣描述的:
1
2
3
4
5
|
""" S.join(iterable) -> str Return a string which is the concatenation of the strings in the iterable. The separator between elements is S. """ |
join()函數(shù)使用時,傳入一個可迭代對象,返回一個可迭代的字符串,該字符串元素之間的分隔符是“S”。
傳入一個可迭代對象,可以使list,tuple,也可以是str。
1
2
3
|
s = 'asdf1234' sss = '@' .join(s) print ( type (sss), sss) |
總結
以上所述是小編給大家介紹的python3 字符串/列表/元組(str/list/tuple)相互轉換方法及join()函數(shù)的使用,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://www.cnblogs.com/zrmw/p/10637114.html