當(dāng)前位置:
首頁 >
python 字符串、列表和元祖之间的切换
發(fā)布時間:2025/7/25
42
豆豆
生活随笔
收集整理的這篇文章主要介紹了
python 字符串、列表和元祖之间的切换
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
>>> 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'?
>>>?
上面的代碼片段是將列表轉(zhuǎn)換成字符串
>>> s=('hello','world','!')?
>>> d=' '.join(s)?
>>> d?
'hello world !'?
>>>?
以上代碼片段將元祖轉(zhuǎn)換成字符串
>>> url='http://www.shein.com'?
>>> s=url.split('.')?
>>> s?
['http://www', 'shein', 'com']?
>>> s=url.split()?
>>> s?
['http://www.shein.com']?
>>>?
上面代碼片段我們可以看出,通過split()方法,我們可以將字符串分割成列表,你也可以指定分割的符號,例如上圖中,以“.”來進(jìn)行分割,得到['http://www', 'shein', 'com']。
注意以下內(nèi)容:
>>> 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?
>>>?
當(dāng)列表的值為數(shù)字時,不能使用join()方法進(jìn)行轉(zhuǎn)換字符串,但我們可以通過for循環(huán),將列表中的數(shù)字轉(zhuǎn)換成字符串。如下所示:
>>> ss=[1,2,3,4]?
>>> s=''?
>>> for i in ss:?
s += str(i)?
>>> s?
'1234'?
轉(zhuǎn)載于:https://www.cnblogs.com/MisterZZL/p/9534302.html
總結(jié)
以上是生活随笔為你收集整理的python 字符串、列表和元祖之间的切换的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: EF框架 对字段属性为NULL的空值处理
- 下一篇: python云计算2