我有一个字符串列表,我想将其转换为单个字符串。
该列表包含我不想用空格分隔的整数。
例如我有以下清单:
lst = ['This', 'house', 'has', 1, 2, 'rooms']
我用来制作字符串的方式是:
' '.join([str(elem) for elem in lst])
这当然会导致:“这所房子有 1 2 个房间”
目的是得到:'这所房子有 12 个房间'
我不确定如何根据列表元素的类型来调节上面的join语句,以便在它是字符串时有空间,如果是 int 则有空字符串。
有什么建议吗?
可能是过度设计的解决方案,但这里是:
' '.join(filter(lambda y: (y != ''), ((''.join([str(' '+x+' ') if type(x) is str else str(x) for x in lst])).strip().split(' '))))
说明:
'This house has 12 rooms'
['This', '', 'house', '', 'has', '12', 'rooms']
['This', 'house', 'has', '12', 'rooms']
它将给出以下输出:
'This house has 12 rooms'
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句