ZetCode

Python 列表转字符串

最后修改于 2024 年 1 月 29 日

Python 列表转字符串教程展示了如何在 Python 中将列表转换为字符串。

要在 Python 中将元素列表转换为单个字符串,我们将使用 joinmapstr 函数和字符串连接运算符。

join 函数返回一个字符串,它是给定可迭代对象中字符串的连接。map 函数返回一个迭代器,它将给定函数应用于可迭代对象的每个项,并产生结果。str 函数将给定对象转换为字符串。

Python 使用 + 运算符连接字符串。

Python 列表转字符串示例

在第一个示例中,我们使用 join 函数将列表转换为字符串。

list2string.py
#!/usr/bin/python

words = ['a', 'visit', 'to', 'London']

slug  = '-'.join(words)
print(slug)

在此示例中,我们从单词列表中创建一个 slug。

$ ./list2string.py 
a-visit-to-London

在下一个示例中,我们使用 join 函数和 Python 列表推导式。

list2string2.py
#!/usr/bin/python

words = ['There', 'are', 3, 'chairs', 'and', 2, 'lamps', 'in', 
    'the', 'room']

msg  = ' '.join(str(word) for word in words)

print(msg)

words 列表中的并非所有元素都是字符串;因此,我们需要在应用 join 函数之前将整数转换为字符串。为此,我们使用 Python 列表推导式结构。

$ ./list2string2.py 
There are 3 chairs and 2 lamps in the room    

或者,我们也可以使用 map 函数。

list2string3.py
#!/usr/bin/python

words = ['There', 'are', 3, 'chairs', 'and', 2, 'lamps', 'in', 
    'the', 'room']

msg  = ' '.join(map(str, words))
print(msg)

我们使用 map 函数将 str 函数应用于列表的每个元素。然后我们使用 join 连接所有元素。

$ ./list2string3.py 
There are 3 chairs and 2 lamps in the room

最后,我们使用字符串连接运算符将列表转换为字符串。

list2string4.py
#!/usr/bin/python

words = ['There', 'are', 3, 'chairs', 'and', 2, 'lamps', 'in', 
    'the', 'room']

msg = ''

for word in words:

    msg += f'{word} '

print(msg)

我们通过 for 循环遍历列表的所有元素。我们使用字符串连接运算符构建字符串。(在我们的例子中是 += 复合运算符。)

$ ./list2string4.py 
There are 3 chairs and 2 lamps in the room 

来源

Python 数据结构 - 语言参考

在本文中,我们在 Python 中将列表转换为字符串。

作者

我叫 Jan Bodnar,我是一名热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 Python 教程