'What am I doing wrong "IndexError: string index out of range"
I'm new to programing . Started learning with Ben Stephenses Python workbook . Everything was going well up till about recently . In few exercises now I'm encountering the same problem . I will give an example with the last one , but the results in the previous was more or less the same . I must say , I'm sure there are better approaches and better ways to do it , but I'm trying to work with what I learned from the book so far which is not a lot . I'm sure that I will find some better solutions online but they will involve stuff I still hasn't learned and I'm trying to not use stuff like that .
Below you can find my code :
x= input("Enter your text: ")
list=[]
word=""
j=0
for j in range (0,len(x)-1):
if x[j]!=" " :
word=word+x[j]
j=j+1
else:
list.append(word)
word=""
j=j+1
print(list)
What I'm trying to do is to separate the words in that string and put it in a list as individual words . If I execute the code as it is , it will put all the words in the list apart form the last one . I kind of think I know why is this happening . I believe cause of the spaces in between the words "j" goes out of range . Is that the case? Or it is something else? If that is the case , how can I deal with that ? If not what is it then ? I tried swapping the "if" with a "while" loop but then I'm getting : "while x[j]!=" " : IndexError: string index out of range"
Thanks !
Solution 1:[1]
One issue with your code is that you have range(0, len(x)-1). The range function produces a range that includes the starting point but excludes the endpoint, e.g.:
>>> list(range(0, 3))
[0, 1, 2]
So you want range(0, len(x)) otherwise you're missing the last character.
As for the omission of the last word:
We rely on seeing a space character to identify when a word ends. This does not work for the last word, since there is no space following it!
To fix this, we can simply add after the loop:
if word:
list.append(word)
(Note that if word checks that word is non-empty, so we account for the case that the user inputs am empty string.)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nicholas Weston |
