To turn a sentence into a list | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

To turn a sentence into a list

Is it possible to turn a sentence into a list of words and each word of that list into a list of letters? For example: UserSentece = input("Say something ... ") Say something ... I played the piano SentenceList = ["I", "played", "the", "piano"] FirstWordOfSentenceList = ["I"] SecondWordOfSentenceList = ["p", "l", "a", "y", "e", "d"] ThirdWordOfSentenceList = ["t", "h", "e"] FourthWordOfSentenceList = ["p", "i", "a", "n", "o"]

4th Apr 2020, 9:47 AM
Alessandro
8 Answers
+ 5
This can be done with a nested comprehension. The inner comprehension is separating the words with split(), the outer comprehension is taking the separated words and separate them to characters. txt = 'This is cool' print([list(j) for j in [i for i in txt.split(' ')]]) # output: ''' [['T', 'h', 'i', 's'], ['i', 's'], ['c', 'o', 'o', 'l']] '''
4th Apr 2020, 12:04 PM
Lothar
Lothar - avatar
+ 5
there are a thousand ways if we research😉
5th Apr 2020, 11:46 AM
M Tamim
M Tamim - avatar
+ 4
s='I played the piano' l = list(map(list, s.split())) print(l) output will be [['I'], ['p', 'l', 'a', 'y', 'e', 'd'], ['t', 'h', 'e'], ['p', 'i', 'a', 'n', 'o']]
4th Apr 2020, 10:22 AM
andriy kan
andriy kan - avatar
4th Apr 2020, 9:52 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 3
sentence = input() or 'This is a test' word_list = [*sentence.split(' ')] print(word_list) letter_list = [[*w] for w in word_list] for i, w in enumerate(letter_list): print() print('letters in word %s:' % (i+1),w) print('1st letter of word:', w[0])
4th Apr 2020, 10:29 AM
visph
visph - avatar
+ 2
Lothar That nested comprehension looks amazing
4th Apr 2020, 10:20 PM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
visph Nice 👍
4th Apr 2020, 10:29 AM
Rik Wittkopp
Rik Wittkopp - avatar