HOWTO · Python
如何在 Python 中將列表轉換為字串
本教程演示瞭如何在 Python 中將列表轉換為字串
本頁內容
在 Python 中 str 將列表轉換為字串
我們可以使用 str.join() 方法將具有 str 資料型別元素的列表轉換為字串。
例如,
A = ["a", "b", "c"]
StrA = "".join(A)
print(StrA)
## StrA is "abc"
join 方法連線任意數量的字串,被呼叫該方法的字串被插入每個給定的字串之間。如示例中所示,字串 "" (一個空字串)被插入列表元素之間。
如果要在元素之間新增空格,則應使用
StrA = " ".join(A)
## StrA is "a b c"
在 Python 中 str 將非列表轉換為字串
join 方法需要將 str 資料型別作為給定引數。因此,如果你嘗試轉換 int 型別列表,你將獲得 TypeError。
>>> a = [1,2,3]
>>> "".join(a)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
"".join(a)
TypeError: sequence item 0: expected str instance, int found
int 型別應該先轉換為 str 型別,然後再執行結合操作。
列表推導式
>>> a = [1,2,3]
>>> "".join([str(_) for _ in a])
"123"
map 函式
>>> a = [1,2,3]
>>> "".join(map(str, a))
'123'
map 函式將函式 str 應用於列表 a 中的所有元素,並返回一個可迭代的 map 物件。
"".join() 迭代 map 物件中的所有元素,並將連線的元素作為字串返回。