python 字串、列表和元祖之間的切換
阿新 • • 發佈:2019-01-22
>>> s=['http','://','www','baidu','.com']
>>> url=''.join(s)
>>> url
'http://wwwbaidu.com'
>>>
>>> s=('hello','world','!')
>>> d=' '.join(s)
>>> d
'hello world !'
>>>
>>> url='http://www.shein.com'
>>> s=url.split('.')
>>> s
['http://www', 'shein', 'com']
>>> s=url.split()
>>> s
['http://www.shein.com']
>>>
>>> n=[1,2,3,4]
>>> s=''.join(n)
Traceback (most recent call last):
File " ", line 1, in
s=''.join(n)
TypeError: sequence item 0: expected str instance, int found
>>>
>>> ss=[1,2,3,4]
>>> s=''
>>> for i in ss:
s += str(i)
>>> s
'1234'
>>> url=''.join(s)
>>> url
'http://wwwbaidu.com'
>>>
上面的程式碼片段是將列表轉換成字串
>>> s=('hello','world','!')
>>> d=' '.join(s)
>>> d
'hello world !'
>>>
以上程式碼片段將元祖轉換成字串
>>> url='http://www.shein.com'
>>> s=url.split('.')
>>> s
['http://www', 'shein', 'com']
>>> s=url.split()
>>> s
['http://www.shein.com']
>>>
上面程式碼片段我們可以看出,通過split()方法,我們可以將字串分割成列表,你也可以指定分割的符號,例如上圖中,以“.”來進行分割,得到['http://www', 'shein', 'com']。
注意以下內容:
>>> n=[1,2,3,4]
>>> s=''.join(n)
Traceback (most recent call last):
File " ", line 1, in
s=''.join(n)
TypeError: sequence item 0: expected str instance, int found
>>>
當列表的值為數字時,不能使用join()方法進行轉換字串,但我們可以通過for迴圈,將列表中的數字轉換成字串。如下所示:
>>> ss=[1,2,3,4]
>>> s=''
>>> for i in ss:
s += str(i)
>>> s
'1234'