Separation of a String into Individual Words (Python)
<p>So I have this code here:</p>

<pre><code>#assign a string to variable
x = "example text"
#create set to store separated words
xset = []
#create base word
xword = ""
for letter in x:
    if letter == " ":
        #add word
        xset.append(xword)
        #add space
        xset.append(letter)
        #reset base word
    else:
        #add letter
        xword = xword + letter
        #back to line 9
#print set with separated words
print xset
</code></pre>

<p>So pretty self explanatory, the for function looks at each letter in <code>x</code>, and if it isn't a space it adds it to <code>xword</code> (Imagine it like <code>xword = "examp" + "l"</code>, that would make <code>xword = "exampl"</code>). If it is a space, it adds <code>xword</code> and a space to the set, and resets <code>xword</code>.</p>

<p>My issue comes to the fact that the word <code>"text"</code> is not being included in the final set. When this code is run, and the set is printed, it gives this:`['example', ' ']</p>

<p>So why isn't the <code>"text"</code> appearing in the set?</p>

<p>You need to have one more append after the loop to add the last word</p>

<pre><code>#assign a string to variable
x = "example text"
#create set to store separated words
xset = []
#create base word
xword = ""
for letter in x:
    if letter == " ":
        #add word
        xset.append(xword)
        #add space
        xset.append(letter)
        #reset base word
    else:
        #add letter
        xword = xword + letter
        #back to line 9
xset.append(xword)
#print set with separated words
print xset
</code></pre>

python string python-2.7