Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate or print list elements with a trailing comma in Python

I am having a list as :

>>> l = ['1', '2', '3', '4']

if I use join statement,

>>> s = ', '.join(l)

will give me output as :

'1, 2, 3, 4'

But, what I have to do If I want output as :

'1, 2, 3, 4,'

(I know that I can use string concat but I want to know some better way)

.

like image 350
sam Avatar asked Apr 25 '12 07:04

sam


1 Answers

For str.join() to work, the elements contained in the iterable (i.e. a list here), must be strings themselves. If you want a trailing comma, just add an empty string to the end of your list.

Edit: To flesh it out a bit:

l = map(str, [1,2,3,4])
l.append('')
s = ','.join(l) 
like image 63
Michael Wild Avatar answered Nov 15 '22 20:11

Michael Wild