在 Python 中将集合转换为字符串

Preet Sanghavi 2023年1月30日
  1. 在 Python 中使用 map()join() 函数将集合转换为字符串
  2. 在 Python 中使用 repr() 函数将集合转换为字符串
在 Python 中将集合转换为字符串

本教程演示了如何使用最佳技术将 Python 集转换为字符串。

我们可以采用两种技术进行所需的转换。

  1. 使用 map()join() 函数。
  2. 使用 repr() 函数。

让我们从一个样本集开始。

se = set([1, 2, 3])

现在我们有一个集合,我们将把它转换成一个字符串。

在 Python 中使用 map()join() 函数将集合转换为字符串

在这种方法中,我们将集合中的每个元素转换为一个字符串,然后将它们连接起来得到一个字符串,我们将使用 ',' 作为分隔符。我们通过以下方式做到这一点。

str_new = ", ".join(list(map(str, se)))

在上面的代码中,map() 函数获取每个集合元素并使用 list() 函数将它们转换为存储在列表中的字符串。然后 join() 函数将字符串中的各个字符串元素以',' 作为分隔符并返回单个字符串。

我们现在将打印新字符串以及数据类型。

print(str_new)
print(type(str_new))

上面的代码为我们提供了以下输出。

'1, 2, 3'
<class 'str'>

输出显示我们已将集合转换为字符串。

在 Python 中使用 repr() 函数将集合转换为字符串

这种方法将使用 repr() 函数将我们的集合转换为字符串。我们将使用与上述技术相同的样本集。

我们将创建一个新变量来存储 repr() 函数的返回值。

r_str = repr(se)

正如我们在上面看到的,我们需要将输入集传递给 repr() 函数,它会返回字符串。我们将打印新变量及其数据类型以确保我们的转换成功。

print(r_str)
print(type(r_str))

以上结果为以下输出。

{1, 2, 3}
<class 'str'>

如上所示,我们的集合已成功转换为字符串。

因此,我们成功地学习了多种将 Python 集合转换为字符串的技术。

作者: Preet Sanghavi
Preet Sanghavi avatar Preet Sanghavi avatar

Preet writes his thoughts about programming in a simplified manner to help others learn better. With thorough research, his articles offer descriptive and easy to understand solutions.

LinkedIn GitHub

相关文章 - Python String

相关文章 - Python Set