How do i return a quoted string from a tuple?
Question
I have a tuple of strings that i would want to extract the contents as a quoted string, i.e.
tup=('string1', 'string2', 'string3')
when i do this
main_str = ",".join(tup)
#i get
main_str = 'string1, string2, string3'
#I want the main_str to have something like this
main_str = '"string1", "string2", "string3"'
Gath
Solution
", ".join('"{0}"'.format(i) for i in tup)
or
", ".join('"%s"' % i for i in tup)
OTHER TIPS
Well, one answer would be:
', '.join([repr(x) for x in tup])
or
repr(tup)[1:-1]
But that's not really nice. ;)
Updated: Although, noted, you will not be able to control if resulting string starts with '" or '". If that matters, you need to be more explicit, like the other answers here are:
', '.join(['"%s"' % x for x in tup])
Here's one way to do it:
>>> t = ('s1', 's2', 's3')
>>> ", ".join( s.join(['"','"']) for s in t)
'"s1", "s2", "s3"'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow