Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I turn a list of lists of words into a sentence string?

Tags:

I have this list

[['obytay'], ['ikeslay'], ['ishay'], ['artway']] 

where I need it to look like

obytay ikeslay ishay artway 

Can anybody help? I tried using join but I can't get it to work.

like image 223
user3477556 Avatar asked Mar 30 '14 07:03

user3477556


People also ask

How do I make a list of words into a string?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

How do I convert a list to a string in one line?

To convert a list to a string in one line, use either of the three methods: Use the ''. join(list) method to glue together all list elements to a single string. Use the list comprehension method [str(x) for x in lst] to convert all list elements to type string.

How do you combine a list of words in a sentence in Python?

join() function in Python Combine them into a sentence with the join(sequence) method. The method is called on a seperator string, which can be anything from a space to a dash. This is easier than using the plus operator for every word, which would quickly become tedious with a long list of words.


2 Answers

You have a list in a list so its not working the way you think it should. Your attempt however was absolutely right. Do it as follows:

' '.join(word[0] for word in word_list) 

where word_list is your list shown above.

>>> word_list = [['obytay'], ['ikeslay'], ['ishay'], ['artway']] >>> print ' '.join(word[0] for word in word_list) obytay ikeslay ishay artway 

Tobey likes his wart

like image 72
sshashank124 Avatar answered Oct 19 '22 11:10

sshashank124


It is a list of strings. So, you need to chain the list of strings, with chain.from_iterable like this

from itertools import chain print " ".join(chain.from_iterable(strings)) # obytay ikeslay ishay artway 

It will be efficient if we first convert the chained iterable to a list, like this

print " ".join(list(chain.from_iterable(strings))) 
like image 33
thefourtheye Avatar answered Oct 19 '22 12:10

thefourtheye