Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to join the elements of a list but keep the '' around element after joining

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?

like image 407
flamenco Avatar asked Nov 25 '25 16:11

flamenco


1 Answers

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'"
like image 85
vaultah Avatar answered Nov 28 '25 15:11

vaultah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!