3

I have this code:

 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

wherein the output is a list of single element tuple (ex. I enter we all there): [('tore',), ('ngaming',), ('sittam',)] (translate the input into mother tongue language). I want that the output will be converted into string to eliminate the [],(),'',' symbols. How to convert it into string?

2 Answers 2

7

You have to use str.join method.

>>> a = [('tore',), ('ngaming',), ('sittam',)]
>>> " ".join([x[0] for x in a])
'tore ngaming sittam'
Sign up to request clarification or add additional context in comments.

7 Comments

@TomByler, it works, you can select it as answer. That will help others to find correct answer.
Another question is how can I convert the single element tuple into an array or how to store the string into an array variable?
You can convert using [x[0] for x in a]
Yes, is that not the same like in single element tuple - string conversion? What if instead of string, the result in this line result = self.cur.fetchall() will be stored in an array variable? Can I do this array[]=result?
@TomByler, better to ask another question with full details.
|
0

I would just use a for loop. You can loop through the list of tuples and add each element to an empty string variable

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

print z

After seeing Lafada's answer, I realized that list comprehension and str.join is the best option. Though his answer is better, this is basically what his answer does, just done more manually.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.