如何从字符串列表中生成逗号分隔的字符串? [英] How would you make a comma-separated string from a list of strings?

查看:27
本文介绍了如何从字符串列表中生成逗号分隔的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从序列中连接字符串以便在每两个连续对之间添加逗号的首选方法是什么.也就是说,例如,如何将 ['a', 'b', 'c'] 映射到 'a,b,c'?(case ['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)

'a,b,c,d'

如果列表包含整数,这将不起作用

This won't work if the list contains integers

如果列表包含非字符串类型(例如整数、浮点数、布尔值、无),则执行:

And if the list contains non-string types (such as integers, floats, bools, None) then do:

my_string = ','.join(map(str, my_list)) 

这篇关于如何从字符串列表中生成逗号分隔的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆