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.
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.
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.
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.
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
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With