0

I've a list of names:

a = ['Maria','Luis','Andrea']

I want to put them in a string, so I make this:

names = ''
for name in a:
    names = names +',' ' ' + name

There's a problem, in the first iteretation I add a comma and a space at the beginning, I know I can just delete the comma and the space but I would prefer just to not have it.

Also, can that be done in a lambda function?

Luis Ramon Ramirez Rodriguez
  • 9,591
  • 27
  • 102
  • 181

3 Answers3

6

Let the str.join() handle that:

>>> a = ['Maria','Luis','Andrea']
>>> ", ".join(a)
'Maria, Luis, Andrea'
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Don't you feel just a little bit guilty answering obvious duplicates instead of voting to close them? – cimmanon Feb 14 '16 at 01:18
  • @cimmanon you definitely have a valid point. I don't go into general Python on SO often, when I do, I usually vote to close in similar cases, but here rushed into answering. So, yes, I feel guilty. Thanks :) – alecxe Feb 14 '16 at 01:23
2

That's what the str.join method is for:

>>> ', '.join(a)
'Maria, Luis, Andrea

The method concatinates all the elements from an iterable with the string join is being called on as the separator.

Some examples:

>>> 'SEP'.join(a)
'MariaSEPLuisSEPAndrea'
>>> ''.join(a)
'MariaLuisAndrea'

It can be seen as the counterpart of str.split:

>>> s = ', '.join(a)
>>> s
'Maria, Luis, Andrea'
>>> s.split(', ')
['Maria', 'Luis', 'Andrea']
timgeb
  • 76,762
  • 20
  • 123
  • 145
2

The correct pythonic way is the ",".join(...) method given in the other answers. However the language agnostic method would be something like this:

for i in range(len(a)):
   if i == 0:
      names += a[i]
   else:
      names += ',' + a[i]
Chad S.
  • 6,252
  • 15
  • 25