今天在寫python的時候,忽然要將列表中的內容轉換成字符串,因而進行了簡單的實驗,記錄下來,方便回憶和使用。python
直接看代碼吧:shell
>>> s=['http','://','www','baidu','.com'] >>> url=''.join(s) >>> url 'http://wwwbaidu.com' >>>
上面的代碼片斷是將列表轉換成字符串url
>>> s=('hello','world','!') >>> d=' '.join(s) >>> d 'hello world !' >>>
以上代碼片斷將元祖轉換成字符串code
>>> 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']。字符串
注意如下內容:it
>>> n=[1,2,3,4] >>> s=''.join(n) Traceback (most recent call last): File "<pyshell#47>", line 1, in <module> s=''.join(n) TypeError: sequence item 0: expected str instance, int found >>>
當列表的值爲數字時,不能使用join()方法進行轉換字符串,但咱們能夠經過for循環,將列表中的數字轉換成字符串。以下所示:for循環
>>> ss=[1,2,3,4] >>> s='' >>> for i in ss: s += str(i) >>> s '1234' >>>
以上就是今天記錄的所有了,雖然是很小的知識點,但到用時,仍是很容易被忽略的。ast