python 字符串、列表和元祖之间的切换
生活随笔
收集整理的這篇文章主要介紹了
python 字符串、列表和元祖之间的切换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
>>> 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'?
轉載于:https://www.cnblogs.com/MisterZZL/p/9534302.html
總結
以上是生活随笔為你收集整理的python 字符串、列表和元祖之间的切换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: EF框架 对字段属性为NULL的空值处理
- 下一篇: mongodb 主从配置,带auth验证