2

my list is:

example = ['a', 'b', 'c']

If I use ",".join(example) , removes ' ' around the elements.

I want my output to be:

example = "'a','b','c'"

Any elegant way to do it?

flamenco
  • 2,702
  • 5
  • 30
  • 46

3 Answers3

4

Not sure if it's elegant, but it works (based on the default representation of list objects and therefore not flexible at all):

>>> example = ['a', 'b', 'c']
>>> repr(example)[1:-1] # [1:-1] to remove brackets
"'a', 'b', 'c'"

Another one (easily customizable):

>>> example = ['a', 'b', 'c']
>>> "'{joined}'".format(joined="', '".join(example))
"'a', 'b', 'c'"

Something like this was already suggested by others, but still:

>>> example = ['a', 'b', 'c']
>>> ', '.join([repr(x) for x in example])
"'a', 'b', 'c'"
vaultah
  • 44,105
  • 12
  • 114
  • 143
  • Your second solution is actually the fastest one of all the proposed solutions so far. I think @imiu deserves a few more upvotes for his question giving us something interesting to discuss. – Tim Pietzcker May 04 '14 at 16:47
  • @TimPietzcker and the first one is twice as slow as the second. – vaultah May 05 '14 at 05:08
3
','.join(map(repr,example))
Out[74]: "'a','b','c'"
roippi
  • 25,533
  • 4
  • 48
  • 73
  • +1, although I'd use a generator expression `",".join(repr(item) for item in example)` instead of `map()`. – Tim Pietzcker May 04 '14 at 16:29
  • IIRC `str.join` actually works better on materialized lists rather than on gen expressions. – roippi May 04 '14 at 16:32
  • @TimPietzcker `.join` needs a total size of a submitted iterable to allocate memory for a new string *before* the joining process starts, so it will firstly unroll the generator. – vaultah May 04 '14 at 16:38
  • @frostnational, roippi: That makes sense, thanks! I've added a CW answer with some timings. The `map()` approach is still the fastest, even though Guido would have liked to remove it from the language in favor of listcomps/genexps. Interesting. – Tim Pietzcker May 04 '14 at 16:44
  • Thak you all! This is my first time posting a question here but you got me hooked! Cheers! – flamenco May 04 '14 at 17:06
2

Just a few timings:

>>> import timeit
>>> setup = 'example = list("abcdefghijklmnop")'
>>> timeit.timeit(setup=setup, stmt = '",".join(repr(item) for item in example)')
4.316254299507404
>>> timeit.timeit(setup=setup, stmt = '",".join([repr(item) for item in example])')
3.393636402412758
>>> timeit.timeit(setup=setup, stmt = '",".join(map(repr, example))')
3.2305143115811887
>>> timeit.timeit(setup=setup, stmt = '''"'{joined}'".format(joined="','".join(example))''')
1.308451301197806
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561