6

This is probably seriously easy to solve for most of you but I cannot solve this simply putting str() around it can I?

I would like to convert this list: ['A','B','C'] into 'A B C'.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
sat_s
  • 277
  • 1
  • 5
  • 11
  • Does this answer your question? [Convert a list of characters into a string](https://stackoverflow.com/questions/4481724/convert-a-list-of-characters-into-a-string) – Tomerikoo Jan 19 '22 at 10:58

3 Answers3

15
In [1]: L = ['A', 'B', 'C']
In [2]: " ".join(L)
Out[2]: 'A B C'
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • just a quick note here: you can use *any* string there and it will join together list items. So if you wanted to join your items with newlines, you could use `'\n'.join(L)`. or if you wanted to get crazy: `' is crazy! '.join(L)` – Jeff Tratner Jun 09 '12 at 06:05
0

I do not like Python's syntax for joining a list of items, so I prefer to call my own function to perform that task, rather than using Python's syntax in line.

Here is my function:

def joinList(l, c):
    return c.join(l)


myList = ['a', 'b', 'c']
myStrg = joinList(myList, "-")

print myStrg
octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
Michael
  • 83
  • 4
  • 3
    "Not liking the syntax" is not a very good excuse to write inefficient code. – Junuxx Jun 09 '12 at 03:20
  • 4
    Junuxx has a good point. However, if you REALLY REALLY hate the syntax, you can use the built-in version: `str.join(' ', ['A', 'B', 'C'])`. – Casey Kuball Jun 09 '12 at 03:53
  • You just quoted the moderator. My comments were much shorter, even if the code does suck. :/ – Michael Jul 06 '12 at 18:49
  • @Michael I upvote for this since I don't like python's `''.join` syntax, either. :-) But actually your code not only work on lists, so I suggest change the name to something like joinIter. Or just use `str.join` as @Darthfett suggested. – weakish Sep 26 '12 at 14:25
0

Let me highlight that join is a method of string, not one of list (actually, it can deal with any iteratable, even dicts):

myList = ['one', 'another', 'next']
separator = ", "
separator.join(myList)

will result in

'one, another, next'
YakovL
  • 7,557
  • 12
  • 62
  • 102