Solusin
Solusin

Reputation: 1

Separation of a String into Individual Words (Python)

So I have this code here:

#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

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

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

So why isn't the "text" appearing in the set?

Upvotes: 0

Views: 87

Answers (3)

semenoff
semenoff

Reputation: 73

Just use string.split(). This command will return list of word in your string. Here is documentation on it: https://docs.python.org/2/library/string.html

If your values are space separated do something like this:

r.split()
Out[26]: ['some', 'text', 'here']

If your seperator different from space you can specify it like this:

s.split(',')
Out[21]: ['some', 'text', 'here']

Upvotes: 0

Farhan.K
Farhan.K

Reputation: 3485

Because when your code reaches the space in x it appends xword. But this only happens when it reaches a space. As there are no spaces after text, the final result is not appended to xset Also, you were not resetting xword:

#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
        xword = ""
    else:
        #add letter
        xword = xword + letter
        #back to line 9
#print set with separated words
xset.append(xword)
print xset

Output:

['example', ' ', 'text']

Upvotes: 1

Arun Ghosh
Arun Ghosh

Reputation: 7764

You need to have one more append after the loop to add the last word

#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

Upvotes: 0

Related Questions