Python列表到字符串教程展示了如何在Python中将列表转换为字符串。
要在Python中将元素列表转换为单个字符串,我们将使用join
、map
、str
函数和字符串连接运算符。
join
函数返回一个字符串,它是给定可迭代对象中字符串的串联。map
函数返回迭代器,该迭代器将给定函数应用于可迭代的每个项目,从而产生结果。str
函数将给定对象转换为字符串。
Python使用+
运算符连接字符串。
Python列表到字符串示例
在第一个示例中,我们使用join
函数将列表转换为字符串。
#!/usr/bin/python words = ['a', 'visit', 'to', 'London'] slug = '-'.join(words) print(slug)
在示例中,我们从单词列表中创建了一个slug。
$ ./list2string.py a-visit-to-London
在下一个示例中,我们使用join
函数和Python列表理解。
#!/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
函数。
#!/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
最后,我们使用字符串连接运算符将列表转换为字符串。
#!/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教程。