0

I'm new to python and I'm trying to take words in a string and put them into a list, but I'm having trouble. This is what it should look like:

Input: sentence = "abcde that i like."

Output: list_of_words = ['abcde', 'that', 'i', 'like.']

This is what I've tried:

word = "" 
list_of_words = []
sentence = "abcde that i like."
for letter in sentence:
  if letter != " ":
    word += letter 
  else:
    list_of_words.append(word)
    word = ""
print(list_of_words)

When I run the code the output is:

['abcde', 'that', 'i']

I'm trying to figure it out why the last word isn't included in the list.

KaiserKatze
  • 1,521
  • 2
  • 20
  • 30
  • 2
    You could always use `.split()`, eh. As for why the last word is not included, try walking through the final few iterations of the loop yourself. – AMC Jan 17 '20 at 01:28
  • 2
    Thanks, I didn't know .split() existed that's super useful. The last word isn't appended because the sentence doesn't end with a space, totally didn't realize that. I went over the final few interations a couple of times but for some reason I didn't go all the way to the end. – Thromobocytin Jan 17 '20 at 01:34
  • You're only checking spaces, not periods or other punctuation – OneCricketeer Jan 17 '20 at 01:34

1 Answers1

1

You shoul simply use str.split():

>>> sentence = "abcde that i like."
>>> list_of_words = sentence.split()
>>> list_of_words
['abcde', 'that', 'i', 'like.']

If you want better results without punctuations, such as the period '.' in the demonstration, you should try regular expression:

>>> import re
>>> re.findall(r'\w+', sentence)
['abcde', 'that', 'i', 'like']

Read more here: re — Regular expression operations — Python 3.8.1 documentation!

KaiserKatze
  • 1,521
  • 2
  • 20
  • 30