Concatenate or print list elements with a trailing comma in Python

20,828

Solution 1

String concatenation is the best way:

l = ['1', '2', '3', '4']  # original list
s = ', '.join(l) + ','

but you have other options also:

  1. Mapping to comma-ended strings, then joining:

    l = ['1', '2', '3', '4']  # original list
    s = ' '.join(map(lambda x: '%s,' % x, l))
    
  2. Appending empty string to the joined list (don't modify original l list!):

    l = ['1', '2', '3', '4']  # original list
    s = ', '.join(l + ['']).rstrip(' ')
    
  3. Using string formatting in place of concatenation:

    l = ['1', '2', '3', '4']  # original list
    s = '%s,' % (', '.join(l))
    

Solution 2

If you are in Python 3, you could leverage the print built-in function:

print(*l, sep=', ', end=',')
  • *l unpacks the list of elements to pass them as individual arguments to print
  • sep is an optional argument that is set to in between elements printed from the elements, here I set it to ', ' with a space as you require
  • end is an optional argument that will be pushed at the and of the resulting printed string. I set it to ',' without space to match your need

You can use it starting Python 2.6 by importing the print function

from __future__ import print_function

However going this way has several caveats:

  • This is assuming you want to output the resulting string in stdout ; or you can redirect the output in a file with the file optional argument into a file
  • if you are in Python 2, the __future__ import can break you code compatibility so you would need to isolate your code in a separate module if the rest of your code is not compatible.

Long story short, either this method or the other proposed answers are a lot of efforts to try to avoid just adding a +',' at the end of the join resulting string

Solution 3

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) 

Solution 4

Firstly, ','.join(l) won't work at all since it requires the elements to be strings, which they are not.

You can fix that and add the trailing comma like so:

In [4]: ', '.join(map(str, l)) + ','
Out[4]: '1, 2, 3, 4,'

I think this is by far the cleanest way to do it.

Solution 5

If you don't want concatenation, things could be hacky...

>>> l = [1, 2, 3, 4]
>>> repr(l+[0])[1:-3] # or str
'1, 2, 3, 4,'
Share:
20,828
sam
Author by

sam

Updated on January 01, 2020

Comments

  • sam
    sam over 4 years

    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)

    .

  • Tadeck
    Tadeck about 12 years
    @aix: I agree about the requirement.
  • georg
    georg about 12 years
    @aix: not really. Imagine their separator is more complex than just a comma (maybe even an expression) and they don't want to repeat it twice or use an temporary variable. Makes perfectly sense to me.
  • NPE
    NPE about 12 years
    @thg435: Well, in the OP's example the two separators are not the same. One is ", " and the other is "," (note the missing space). I therefore don't really see how your argument applies here.
  • okm
    okm about 12 years
    You might want to change l to s for all options or vice-verse?
  • sdaau
    sdaau over 9 years
    Thanks @MichaelWild - I was wondering why I kept getting a trailing comma in my code, and it turns out that was because the last entry in the array I had was the empty string. Cheers!
  • wjandrea
    wjandrea almost 3 years
    map(lambda) is ugly IMO. Use a generator expression instead: '%s,' % x for x in l