python 字串 列表和元祖之間的切換

2022-08-18 17:36:13 字數 977 閱讀 9174

上面的**片段是將列表轉換成字串

>>> s=('hello','world','!') 

>>> d=' '.join(s) 

>>> d 

'hello world !' 

>>> 

以上**片段將元祖轉換成字串

上面**片段我們可以看出,通過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' 

Python字串,列表,元祖,字典

python中的字串。比如 str hello world 就是字串,python中字串也可以用單引號包裹,str hello world 字串的下標與切片。字串可以理解為字元的陣列,所以支援下標索引,下標從0開始,比如 str summer str 0 就是 s 如果想取出部分字元,可以通過下標獲...

python基礎語法 字串 列表 元祖 字典

切片是指對操作的物件擷取其中一部分的操作。字串 列表 元組都支援切片操作。join適用於字串和列表 字串的replace方法,字串名.replace old,new,count 預設情況下全部替換 partition分隔為元祖,包含三部分,str前,str,str後 split 以 str 為分隔符...

Python 字串 列表和元組

如下 指定下標 string 1 list print string 1 0 執行結果 l print string 1 1 執行結果 t 字串的拼接 string 1 你好,string 2 世界!string 3 string 1 string 2 print string 3 執行結果 你好,...