在Python中使用尾随逗号连接或打印列表元素 [英] Concatenate or print list elements with a trailing comma in Python
本文介绍了在Python中使用尾随逗号连接或打印列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的列表为:
>>> l = ['1', '2', '3', '4']
如果我使用join语句,
if I use join statement,
>>> s = ', '.join(l)
将给我输出为:
'1, 2, 3, 4'
但是,如果我想输出为:
But, what I have to do If I want output as :
'1, 2, 3, 4,'
(我知道我可以使用字符串concat,但是我想知道一些更好的方法)
(I know that I can use string concat but I want to know some better way)
.
推荐答案
字符串串联是最好的方法:
String concatenation is the best way:
l = ['1', '2', '3', '4'] # original list
s = ', '.join(l) + ','
但是您还有其他选择:
-
映射为逗号结尾的字符串,然后加入:
Mapping to comma-ended strings, then joining:
l = ['1', '2', '3', '4'] # original list
s = ' '.join(map(lambda x: '%s,' % x, l))
在连接列表中添加空字符串(不要修改原始的 l
列表!):
l = ['1', '2', '3', '4'] # original list
s = ', '.join(l + ['']).rstrip(' ')
使用字符串格式代替串联:
Using string formatting in place of concatenation:
l = ['1', '2', '3', '4'] # original list
s = '%s,' % (', '.join(l))
这篇关于在Python中使用尾随逗号连接或打印列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文