I’m currently learning python from a book called ‘Python for the absolute beginner (third edition)’. There is an exercise in the book which outlines code for a hangman game. I followed along with this code however I keep getting back an error in the middle of the program.
Here is the code that is causing the problem:
if guess in word:
print("nYes!", guess, "is in the word!")
# Create a new variable (so_far) to contain the guess
new = ""
i = 0
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += so_far[i]
so_far = new
This is also the error it returns:
new += so_far[i]
IndexError: string index out of range
Could someone help me out with what is going wrong and what I can do to fix it?
edit: I initialised the so_far variable like so:
so_far = "-" * len(word)
asked Jan 3, 2012 at 12:58
DarkphenomDarkphenom
6472 gold badges8 silver badges14 bronze badges
2
It looks like you indented so_far = new
too much. Try this:
if guess in word:
print("nYes!", guess, "is in the word!")
# Create a new variable (so_far) to contain the guess
new = ""
i = 0
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += so_far[i]
so_far = new # unindented this
answered Jan 3, 2012 at 13:25
Rob WoutersRob Wouters
15.7k3 gold badges42 silver badges36 bronze badges
1
You are iterating over one string (word
), but then using the index into that to look up a character in so_far
. There is no guarantee that these two strings have the same length.
answered Jan 3, 2012 at 13:00
unwindunwind
390k64 gold badges468 silver badges605 bronze badges
This error would happen when the number of guesses (so_far) is less than the length of the word. Did you miss an initialization for the variable so_far somewhere, that sets it to something like
so_far = " " * len(word)
?
Edit:
try something like
print "%d / %d" % (new, so_far)
before the line that throws the error, so you can see exactly what goes wrong. The only thing I can think of is that so_far is in a different scope, and you’re not actually using the instance you think.
answered Jan 3, 2012 at 13:02
CNeoCNeo
7261 gold badge6 silver badges10 bronze badges
3
There were several problems in your code.
Here you have a functional version you can analyze (Lets set ‘hello’ as the target word):
word = 'hello'
so_far = "-" * len(word) # Create variable so_far to contain the current guess
while word != so_far: # if still not complete
print(so_far)
guess = input('>> ') # get a char guess
if guess in word:
print("nYes!", guess, "is in the word!")
new = ""
for i in range(len(word)):
if guess == word[i]:
new += guess # fill the position with new value
else:
new += so_far[i] # same value as before
so_far = new
else:
print("try_again")
print('finish')
I tried to write it for py3k with a py2k ide, be careful with errors.
answered Jan 3, 2012 at 13:33
joaquinjoaquin
82.3k29 gold badges138 silver badges152 bronze badges
1
The python error IndexError: string index out of range occurs if a character is not available at the string index. The string index value is out of range of the String length. The python error IndexError: string index out of range occurs when a character is retrieved from the out side index of the string range.
The IndexError: string index out of range error occurs when attempting to access a character using the index outside the string index range. To identify a character in the string, the string index is used. This error happens when access is outside of the string’s index range.
If the character is retrieved by an index that is outside the range of the string index value, the python interpreter can not locate the location of the memory. The string index starts from 0 to the total number of characters in the string. If the index is out of range, It throws the error IndexError: string index out of range.
A string is a sequence of characters. The characters are retrieved by the index. The index is a location identifier for the ordered memory location where character is stored. A string index starts from 0 to the total number of characters in the string.
Exception
The IndexError: string index out of range error will appear as in the stack trace below. Stack trace shows the line the error has occurred at.
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 2, in <module>
print ("the value is ", x[6])
IndexError: string index out of range
[Finished in 0.1s with exit code 1]
Root cause
The character in the string is retrieved via the character index. If the index is outside the range of the string index the python interpreter can’t find the character from the location of the memory. Thus it throws an error on the index. The string index starts from 0 and ends with the character number in the string.
Forward index of the string
Python allows two forms of indexing, forward indexing and backward indexing. The forward index begins at 0 and terminates with the number of characters in the string. The forward index is used to iterate a character in the forward direction. The character in the string will be written in the same index order.
Index | 0 | 1 | 2 | 3 | 4 |
Value | a | b | c | d | e |
Backward index of the string
Python allows backward indexing. The reverse index starts from-1 and ends with the negative value of the number of characters in the string. The backward index is used to iterate the characters in the opposite direction. In the reverse sequence of the index, the character in the string is printed. The back index is as shown below
Index | -5 | -4 | -3 | -2 | -1 |
Value | a | b | c | d | e |
Solution 1
The index value should be within the range of String. If the index value is out side the string index range, the index error will be thrown. Make sure that the index range is with in the index range of the string.
The string index range starts with 0 and ends with the number of characters in the string. The reverse string index starts with -1 and ends with negative value of number of characters in the string.
In the example below, the string contains 5 characters “hello”. The index value starts at 0 and ends at 4. The reverse index starts at -1 and ends at -5.
Program
x = "hello"
print "the value is ", x[5]
Output
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 2, in <module>
print "the value is ", x[5]
IndexError: string index out of range
[Finished in 0.0s with exit code 1]
Solution
x = "hello"
print "the value is ", x[4]
Output
the value is o
[Finished in 0.1s]
Solution 2
If the string is created dynamically, the string length is unknown. The string is iterated and the characters are retrieved based on the index. In this case , the value of the index is unpredictable. If an index is used to retrieve the character in the string, the index value should be validated with the length of the string.
The len() function in the string returns the total length of the string. The value of the index should be less than the total length of the string. The error IndexError: string index out of range will be thrown if the index value exceeds the number of characters in the string
Program
x = "hello"
index = 5
print "the value is ", x[index]
Output
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 3, in <module>
print "the value is ", x[index]
IndexError: string index out of range
[Finished in 0.1s with exit code 1]
Solution
x = "hello"
index = 4
if index < len(x) :
print "the value is ", x[index]
Output
the value is o
[Finished in 0.1s]
Solution 3
Alternatively, the IndexError: string index out of range error is handled using exception handling. The try block is used to handle if there is an index out of range error.
x = "hello"
print "the value is ", x[5]
Exception
the value is
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 2, in <module>
print "the value is ", x[5]
IndexError: string index out of range
[Finished in 0.1s with exit code 1]
Solution
try:
x = "hello"
print "the value is ", x[5]
except:
print "not available"
Output
the value is not available
[Finished in 0.1s]
The Python IndexError: string index out of range
error occurs when an index is attempted to be accessed in a string that is outside its range.
What Causes IndexError: string index out of range
This error occurs when an attempt is made to access a character in a string at an index that does not exist in the string. The range of a string in Python is [0, len(str) - 1]
, where len(str)
is the length of the string. When an attempt is made to access an item at an index outside this range, an IndexError: string index out of range
error is thrown.
Python IndexError: string index out of range Example
Here’s an example of a Python IndexError: string index out of range
thrown when trying to access a character outside the index range of a string:
my_string = "hello"
print(my_string[5])
In the above example, since the string my_string
contains 5 characters, its last index is 4. Trying to access a character at index 5 throws an IndexError: string index out of range
:
Traceback (most recent call last):
File "test.py", line 2, in <module>
print(my_string[5])
~~~~~~~~~^^^
IndexError: string index out of range
How to Handle IndexError: string index out of range in Python
The Python IndexError: string index out of range
can be fixed by making sure any characters accessed in a string are within the range of the string. This can be done by checking the length of the string before accessing an index. The len()
function can be used to get the length of the string, which can be compared with the index before it is accessed.
If the index cannot be known to be valid before it is accessed, a try-except block can be used to catch and handle the error:
my_string = "hello"
try:
print(my_string[5])
except IndexError:
print("Index out of range")
In this example, the try
block attempts to access the 5th index of the string, and if an IndexError
occurs, it is caught by the except
block, producing the following output:
Index out of range
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!
In this Python tutorial, we will discuss how to fix the error indexerror: string index out of range in Python. We will check how to fix the error indexerror string index out of range python 3.
In python, an indexerror string index out of range python error occurs when a character is retrieved by an index that is outside the range of string value, and the string index starts from ” 0 “ to the total number of the string index values.
Example:
name = "Jack"
value = name[4]
print(value)
After writing the above code (string index out of range), Ones you will print “ value” then the error will appear as an “ IndexError: string index out of range ”. Here, the index with name[4] is not in the range, so this error arises because the index value is not present and it is out of range.
You can refer to the below screenshot for string index out of range
This is IndexError: string index out of range.
To solve this IndexError: string index out of range we need to give the string index in the range so that this error can be resolved. The index starts from 0 and ends with the number of characters in the string.
Example:
name = "Jack"
value = name[2]
print('The character is: ',value)
After writing the above code IndexError: string index out of range this is resolved by giving the string index in the range, Here, the index name[2] is in the range and it will give the output as ” The character is: c ” because the specified index value and the character is in the range.
You can refer to the below screenshot on how to solve the IndexError: string index out of range.
So, the IndexError is resolved string index out of range.
You may like the following Python tutorials:
- SyntaxError: Unexpected EOF while parsing
- ValueError: Invalid literal for int() with base 10 in Python
This is how to solve IndexError: string index out of range in Python or indexerror string index out of range Python 3.
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.
Surprise, surprise! We’re back with another article on a Python exception. Of course, this time we’re moving away from the SyntaxError and into a more specialized error, the IndexError, which is accompanied by various error messages. The error message we’ll be talking about today reads: `IndexError: string index out of range`raw.
In case you’re short on time, this IndexError arises when a string is accessed using an invalid index. For example, the string “VirtualFlat” has 11 characters. If a user were to try to access a character beyond this limit—say `”VirtualFlat”[15]`python—an IndexError would arise.
In the remainder of this article, we’ll look at this IndexError more deeply. For instance, we’ll take a look at the IndexError broadly. Then, we’ll hone in on the specific message. After that, we’ll wrap things up with some potential solutions and offer up an opportunity to share your code if you’re still having trouble.
Table of Contents
What Is an IndexError?
According to Python documentation, an IndexError is raised whenever “a sequence subscript is out of range.” Of course, what does that really mean?
To break down this definition, we need to understand a few terms. First, a sequence is a list-like object where items are stored in order; think lists, strings, and tuples. In this context, a subscript is then another name for an item’s index.
In Python, for an index to be out of range, it must not exist. For example, if we had a string like “VirtualFlat”, a valid index would be any value less than the length of the string and greater than or equal to the negative length of the string:
# Declare some index brand = "VirtualFlat" is_valid_index = -len(brand) <= index < len(brand)
As we can see, the range of indices is actually asymmetric. This is because negative indexing starts from negative one—as opposed to zero during regular indexing.
On a side note, I probably should have represented the range mathematically, but I struggled to come up with a syntax where the length operator wasn’t the exact same operator as absolute value (i.e. `|x|`). Also, the lack of symmetry made the expression clunky either way. I would have preferred something like `|index| < |brand|`, but it ends up being `-|brand| <= index < |brand|`. Perhaps interval notation would be a bit cleaner: `[-|brand|, |brand|)`.
At any rate, all this means is that there are valid and invalid indices. For instance, the following code snippets will result in an IndexError:
brand = "VirtualFlat" brand[17] # out of range brand[-12] # out of range
Of course, this same idea applies to any sequence type. For example, we could see this same error turn up for any of the following sequences:
nums = [1, 4, 5] nums[7] # IndexError: list index out of range
nums = (1, 4, 5) nums[7] # IndexError: tuple index out of range
nums = range(5) nums[7] # IndexError: range object index out of range
In the next section, we’ll take a look at this error in the context of its error message.
What Does This IndexError Message Mean?
Up to this point, we’ve talked about the IndexError broadly, but the error message we’re dealing with gives us a bit more information: `IndexError: string index out of range`raw.
Here, we can see that we’re not dealing with a list or tuple. Instead, we’re working with a string. As a result, our original example still holds:
brand = "VirtualFlat" brand[17] # out of range brand[-12] # out of range
That said, there are other ways we could get this error message to arise. For example, the Formatter class of string can throw the same error when using the `get_value()`python method.
In fact, there are probably thousands of libraries that could throw this error, so it’s tough for me to assume your situation. As a result, in the next section, we’ll take a look at the simple case and try to come up with some general problem solving strategies.
How to Fix This IndexError?
Now that we know we have some sort of indexing issue with our string, it’s just a matter of finding the root cause.
Like the original scenario we explores, it’s possible that we have some hardcoded value that is breaching the range of our string:
brand = "VirtualFlat" brand[17] # out of range
In this case, we’ll probably want to generate a constant from this index and give it a good name. After all, maintaining a magic number is usually a bad idea:
brand = "VirtualFlat" LAST_CHAR = 10 brand[LAST_CHAR]
Having solved our magic number issue, I’d argue that there’s an even better solution: we should compute the last character programatically. Of course, if we’re not careful, we could find ourselves with yet another IndexError:
brand = "VirtualFlat" brand[len(brand)] # out of range, again
To get the last character, we’ll need to subtract one from the length:
brand = "VirtualFlat" brand[len(brand) - 1]
That said, if you’ve read my guide to getting the last item of a list, you know there’s an even cleaner solution. Of course, we’re not here to get the last character of a string; we’re trying to anticipate different ways in which this error could arise.
For instance, we might be doing something a bit more complicated like looping over a string:
brand = "VirtualFlat" i = 0 while i <= len(brand): if i % 2 == 0: print(brand[i]) # sometimes out of range
Here, we’ll notice that the loop condition always takes the index one step too far. As a result, we’ll need to correct it:
brand = "VirtualFlat" i = 0 while i < len(brand): if i % 2 == 0: print(brand[i]) # sometimes out of range
Or even better, we can take advantage of the for loop:
brand = "VirtualFlat" for i, c in enumerate(brand): if i % 2 == 0: print(c) # sometimes out of range
Of course, this doesn’t even begin to scratch the realm of possibility for this error. As a result, in the next section, we’ll take a look at getting you some extra help—if you need it!
Need Help Fixing This IndexError?
As someone who has been relieved of their teaching duties for a little while, I figured I’d start sharing my time with the folks of the internet. In other words, if you find this article helpful but didn’t quite give you what you needed, consider sharing your code snippet with me on Twitter.
To do that, you’re welcome to use the #RenegadePython hashtag. Typically, I use that for Python challenges, but I figured I’d open it up for general Python Q&A. Here’s a sample tweet to get you started:
At any rate, that’s all I’ve got for today. If you liked this article, I’d appreciate it if you made your way over to my list of ways to grow the site. There, you’ll find links to my newsletter, YouTube channel, and Patreon.
Likewise, here are a few related articles for your perusal:
- Rock Paper Scissors Using Modular Arithmetic
- How to Get the Last Item of a List in Python
Finally, here are a few additional Python resources on Amazon (ad):
Otherwise, thanks for stopping by and enjoy the rest of your day!
Python Errors (3 Articles)—Series Navigation
As someone trying to build up their collection of Python content, I figured why not create another series? This time, I thought it would be fun to explain common Python errors.