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?
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?
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'"
','.join(map(repr,example))
Out[74]: "'a','b','c'"
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