如何从元组中返回带引号的字符串?
我有一个字符串的元组,我想把里面的内容提取出来,变成一个带引号的字符串,也就是说:
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
3 个回答
0
这里有一种方法可以做到:
>>> t = ('s1', 's2', 's3')
>>> ", ".join( s.join(['"','"']) for s in t)
'"s1", "s2", "s3"'
2
好的,一个答案可以是:
', '.join([repr(x) for x in tup])
或者
repr(tup)[1:-1]
不过这样看起来不太好。;)
更新:虽然要注意,你不能控制结果字符串是否以'"或'"开头。如果这很重要,你需要更明确一些,就像这里其他的答案一样:
', '.join(['"%s"' % x for x in tup])
10
", ".join('"{0}"'.format(i) for i in tup)
或者
", ".join('"%s"' % i for i in tup)