您将如何从字符串列表中创建一个逗号分隔的字符串? [英] How would you make a comma-separated string from a list of strings?
问题描述
从序列连接字符串的首选方式是什么,以便在每两对连续的对之间添加一个逗号.也就是说,如何将例如['a', 'b', 'c']
映射到'a,b,c'
? (案例['s']
和[]
应该分别映射到's'
和''
.)
What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance, ['a', 'b', 'c']
to 'a,b,c'
? (The cases ['s']
and []
should be mapped to 's'
and ''
, respectively.)
我通常最终会使用''.join(map(lambda x: x+',',l))[:-1]
之类的东西,但也会感到有些不满意.
I usually end up using something like ''.join(map(lambda x: x+',',l))[:-1]
, but also feeling somewhat unsatisfied.
推荐答案
my_list = ['a', 'b', 'c', 'd']
my_string = ','.join(my_list)
如果列表中包含数字,则此方法将无效.
This won't work if the list contains numbers.
如果列表包含非字符串类型(例如整数,浮点数,布尔值,无),则请执行以下操作:
And if the list contains non-string types (such as integers, floats, bools, None) then do:
my_string = ','.join(map(str, my_list))
这篇关于您将如何从字符串列表中创建一个逗号分隔的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!