+ 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"]
9 Respuestas
+ 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']]
'''
+ 5
there are a thousand ways if we research😉
+ 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']]
+ 3
See if this helps
https://code.sololearn.com/cY8v12p4bMNm/?ref=app
+ 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])
+ 2
Lothar That nested comprehension looks amazing
+ 2
+ 1
visph Nice 👍