Reputation: 3
I need to take a sentence or simply a set of words, split each word into an individual variable, then list them. This is what I have so far:
sentence = input('Please type a sentence:')
sentence.split(" ")
words = []
words.extend([sentence.split(" ")])
print(words)
I'm using the words "one two three"
as an input to test the code. With this example sentence, the intended output is [one, two, three]
then, I should be able to all on the separate variables later so: words[2]
The problem is that the list "words"
is only receiving the split sentence as one variable single variable so the output becomes [[one, two, three]]
and there's technically only one variable.
Also: I am an utter noob to programming in general, and this is my first post So, forgive me if I've missed something blatantly obvious,
Upvotes: 0
Views: 656
Reputation: 13
try this
words = []
def split(sentence):
words = sentence.split(" ")
return words
words = split("and the duck said: Woof")
print(words)
the code is pretty self explanatory but for the sake of completion:
i make a array called words
i make a function that will split a sentence for us
i call the function and put what is returns in words
and the output look something like this
['and', 'the', 'duck', 'said:', 'Woof']
Upvotes: 0
Reputation: 766
You are passing a list to "words" (which already is a list). You can do either of these two things:
words = sentence.split(" ")
If you want to add more entries later, and want to use the extend function, use :
words = []
words.extend(sentence.split(" "))
Hope this helps.
Upvotes: 0
Reputation: 4420
split
it self returns a list and again you putting in another []
so it getting nested
words.extend(sentence.split(" "))
or you can directly assign the list above
words = sentence.split(' ')
print (words)
#out
[one, two, three]
Upvotes: 0
Reputation:
sentence = input('Please type a sentence:')
templist = sentence.split(" ")
words = []
for x in templist:
words.append(x)
print(words)
OR
Alternative:
sentence = input('Please type a sentence:')
words = sentence.split(" ")
print(words)
Explanation:
Get the sentence to sentence
variable
sentence = input('Please type a sentence:')
Split the sentence using split function with space as delimiter and store in templist
templist = sentence.split(" ")
Iterate over the words in templist and append each word into words
list
for x in templist:
words.append(x)
Upvotes: 0
Reputation: 856
Use
words = sentence.split(" ")
should solve your problem. split
by itself return a list.
Upvotes: 2