Moose
Moose

Reputation: 3

How would I split a sentence into variables, then list it

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

Answers (5)

H_raven
H_raven

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:

  1. i make a array called words

  2. i make a function that will split a sentence for us

  3. 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

Akash Srivastav
Akash Srivastav

Reputation: 766

You are passing a list to "words" (which already is a list). You can do either of these two things:

  • Use : 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

Roushan
Roushan

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

user5777975
user5777975

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

digitake
digitake

Reputation: 856

Use

words = sentence.split(" ")

should solve your problem. split by itself return a list.

Upvotes: 2

Related Questions