如何将单个元素元组转换为字符串?

时间:2015-02-23 04:13:48

标签: python string tuples

我有这段代码:

 import nltk
 import pypyodbc

 text = raw_input()
 token = nltk.word_tokenize(text) //return a list value


def search(self, lists):
    if not self.connected:
        self.connect()
    for word in lists:
        self.cur.execute('SELECT Ybanag FROM Words WHERE English IN (%s)' % (','.join('?'*len(lists))), lists)
        result = self.cur.fetchall()
        return result

其中输出是单个元素元组的列表(例如,我输入we all there):       [('tore',), ('ngaming',), ('sittam',)](将输入翻译成母语)。我希望将输出转换为字符串以消除[],(),'','符号。如何将其转换为字符串?

2 个答案:

答案 0 :(得分:7)

您必须使用str.join方法。

>>> a = [('tore',), ('ngaming',), ('sittam',)]
>>> " ".join([x[0] for x in a])
'tore ngaming sittam'

答案 1 :(得分:0)

我只想使用for循环。您可以循环遍历元组列表并将每个元素添加到空字符串变量

x = [('tore'), ('ngaming'), ('sittam')]
z = ""
for i in x:
    z = z + i + " "

print z

在看到拉法达的回答之后,我意识到列表理解和str.join是最好的选择。虽然他的答案更好,但这基本上就是他的答案,只是手动完成。