在抓取網絡數據的時候,有時會用正則對結構化的數據進行提取,好比 href="https://www.1234.com"等。python的re模塊的findall()函數會返回一個全部匹配到的內容的列表,在將數據存入數據庫時,列表數據類型是不被容許的,而是須要將其轉換爲元組形式。下面看下,str/list/tuple三者之間怎麼相互轉換。python
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()函數來實現 # 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()函數來實現。join()函數是這樣描述的:
""" S.join(iterable) -> str Return a string which is the concatenation of the strings in the iterable. The separator between elements is S. """
join()函數使用時,傳入一個可迭代對象,返回一個可迭代的字符串,該字符串元素之間的分隔符是「S」。數據庫
傳入一個可迭代對象,可使list,tuple,也能夠是str。網絡
s = 'asdf1234' sss = '@'.join(s) print(type(sss), sss)