如何在 Python 中将列表转换为字符串

Jinku Hu 2023年1月30日 2019年12月26日
  1. 在 Python 中 str 将列表转换为字符串
  2. 在 Python 中 str 将非列表转换为字符串
如何在 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 对象中的所有元素,并将连接的元素作为字符串返回。

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

相关文章 - Python String

相关文章 - Python List