Ошибка string index out of range python

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

Darkphenom's user avatar

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 Wouters's user avatar

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

unwind's user avatar

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

CNeo's user avatar

CNeoCNeo

7361 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

joaquin's user avatar

joaquinjoaquin

82.4k29 gold badges138 silver badges152 bronze badges

1

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!

Like lists, Python strings are indexed. This means each value in a string has its own index number which you can use to access that value. If you try to access an index value that does not exist in a string, you’ll encounter a “TypeError: string index out of range” error.

In this guide, we discuss what this error means and why it is raised. We walk through an example of this error in action to help you figure out how to solve it.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

TypeError: string index out of range

In Python, strings are indexed starting from 0. Take a look at the string “Pineapple”:

P i n e a p p l e
0 1 2 3 4 5 6 7 8

“Pineapple” contains nine letters. Because strings are indexed from 0, the last letter in our string has the index number 8. The first letter in our string has the index number 0.

If we try to access an item at position 9 in our list, we’ll encounter an error. This is because there is no letter at index position 9 for Python to read.

The “TypeError: string index out of range” error is common if you forget to take into account that strings are indexed from 0. It’s also common in for loops that use a range() statement.

Example Scenario: Strings Are Indexed From 0

Take a look at a program that prints out all of the letters in a string on a new line:

def print_string(sentence):
	count = 0

	while count <= len(sentence):
		print(sentence[count])
		count += 1

Our code uses a while loop to loop through every letter in the variable “sentence”. Each time a loop executes, our variable “count” is increased by 1. This lets us move on to the next letter when our loop continues.

Let’s call our function with an example sentence:

Our code returns:

S
t
r
i
n
g
Traceback (most recent call last):
  File "main.py", line 8, in <module>
	print_string("test")
  File "main.py", line 5, in print_string
	print(sentence[count])
IndexError: string index out of range

Our code prints out each character in our string. After every character is printed, an error is raised. This is because our while loop continues until “count” is no longer less than or equal to the length of “sentence”.

To solve this error, we must ensure our while loop only runs when “count” is less than the length of our string. This is because strings are indexed from 0 and the len() method returns the full length of a string. So, the length of “string” is 6. However, there is no character at index position 6 in our string.

Let’s revise our while loop:

while count < len(sentence):

This loop will only run while the value of “count” is less than the length of “sentence”.

Run our code and see what happens:

Our code runs successfully!

Example Scenario: Hamming Distance Program

Here, we write a program that calculates the Hamming Distance between two sequences. This tells us how many differences there are between two strings.

Start by defining a function that calculates the Hamming distance:

def hamming(a, b):
	differences = 0

	for c in range(0, len(a)):
		if a[c] != b[c]:
			differences += 1

	return differences

Our function accepts two arguments: a and b. These arguments contain the string values that we want to compare.

In our function, we use a for loop to go through each position in our strings to see if the characters at that position are the same. If they are not the same, the “differences” counter is increased by one.

Call our function and try it out with two strings:

answer = hamming("Tess1", "Test")
print(answer)

Run our code and see what happens:

Traceback (most recent call last):
  File "main.py", line 10, in <module>
	answer = hamming("Tess1", "Test")
  File "main.py", line 5, in hamming
	if a[c] != b[c]:
IndexError: string index out of range

Our code returns an error. This is because “a” and “b” are not the same length. “a” has one more character than “b”. This causes our loop to try to find another character in “b” that does not exist even after we’ve searched through all the characters in “b”.

We can solve this error by first checking if our strings are valid:

def hamming(a, b):
	differences = 0

	if len(a) != len(b):
		print("Strings must be the same length.")
		return 

	for c in range(0, len(a)):
		if a[c] != b[c]:
			differences += 1

	return differences

We’ve used an “if” statement to check if our strings are the same length. If they are, our program will run. If they are not, our program will print a message to the console and our function will return a null value to our main program. Run our code again:

Strings must be the same length.
None

Our code no longer returns an error. Try our algorithm on strings that have the same length:

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

answer = hamming("Test", "Tess")
print(answer)

Our code returns: 1. Our code has successfully calculated the Hamming Distance between the strings “Test” and “Tess”.

Conclusion

The “TypeError: string index out of range” error is raised when you try to access an item at an index position that does not exist. You solve this error by making sure that your code treats strings as if they are indexed from the position 0.

Now you’re ready to solve this common Python error like a professional coder!

IndexError: string index out of range in Python” is a common error related to the wrong index. The below explanations can explain more about the causes of this error and solutions. You will know the way to create a function to check the range.

How does the “TypeError: encoding without a string argument” in Python occur?

Basically, this error occurs when you are working with a string, and you have some statement in your code that attempts to access an out of range index of a string, which may be larger than the total length of the string. For example:

string = 'LearnShareIT'

print(len(string))
print (string[12])

Output

12
Traceback (most recent call last):
  File "code.py", line 4, in <module>
    print (string[12])
IndexError: string index out of range

The example above shows that our string (“LearnShareIT”) has 12 characters. However, it is trying to access index 12 of that string. At first, you may think this is possible, but you need to recall that Python strings (or most programming languages) start at index 0, not 1. This error often occurs with new programmers. To fix the error, we provide you with the following solutions:

How to solve the error?

Create a function to check the range

As we have explained, you cannot access indexes that equal to or exceed the total length of the string. To prevent this happen, you can create your own function, which is used for accessing a string if you provided a valid index, otherwise returns None:

def myFunction(string, index):
    if (index >= -len(string) and index < len(string)):
        return string[index]
    else: return None
    
string = 'LearnShareIT'
print(len(string))
print (myFunction(string,12))

Output

12
None

The above example also works on negative indexes:

print(myFunction(string,-12))

Output

L

The logic behind this method is understandable. We use the len() function to get the total length of a string and use an if statement to make sure the index is smaller than the length and not smaller than the negative length (which is like index 0 also represents the first character of a string). However, this function does not help you to retry with a new index when the error is raised. In the next solution, we can do this by using try catch exception.

Use try-catch exception with loop

Another way to catch the error is to use a while loop to repeatedly ask the user to input the string until the string has enough characters which is able to access the given index:

print('type a string to access the 12th index')
string = input()
print(len(string))

while (True):
    try:
        print (string[12])
        break
    except:
        print('Wrong input, please type again:')
        string = input()

Output

type a string to access the 12th index
LearnShareIT
12
Wrong input, please type again:
LearnShareIT!
!

However, remember that the while loop will run forever if the user keeps on providing invalid strings which are not long enough to access our index. This problem usually occurs when the given index is very big such as 1000:

print('type a string to access the 1000th index')
string = input()
print(len(string))

for i in range (0,5):
    try:
        print (string[1000])
        break
    except:
        print('Wrong input, please type again:')
        string = input()

print("Exit")

Output

type a string to access the 12th index
 
0
Wrong input, please type again:
 
Wrong input, please type again:
 
Wrong input, please type again:
 
Wrong input, please type again:
 
Wrong input, please type again:
 
Exit

To tackle that situation, the above example used the for loop instead of while(true), and the range(0,5) indicates that the loop will run for a maximum of 5 times if the user types invalid inputs.

Summary

In this tutorial, we have helped you to deal with the error “IndexError: string index out of range” in Python. By checking the correct range of the index is smaller than the length of the string, you can easily solve this problem. Good luck to you!

Maybe you are interested:

  • How To Solve AttributeError: ‘Str’ Object Has No Attribute ‘Trim’ In Python
  • How To Resolve AttributeError: ‘str’ Object Has No Attribute ‘append’ In Python
  • How To Solve The Error “ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] Wrong Version Number (_ssl.c:1056)” In Python

I’m Edward Anderson. My current job is as a programmer. I’m majoring in information technology and 5 years of programming expertise. Python, C, C++, Javascript, Java, HTML, CSS, and R are my strong suits. Let me know if you have any questions about these programming languages.


Name of the university: HCMUT
Major: CS
Programming Languages: Python, C, C++, Javascript, Java, HTML, CSS, R

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

indexerror string index out of range python
IndexError: 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.

string index out of range python

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.

Fewlines4Biju Bijay

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.

  • Ошибка strlen was not declared in this scope
  • Ошибка string data right truncation
  • Ошибка string or binary data would be truncated the statement has been terminated
  • Ошибка string cannot be converted to string
  • Ошибка stream read error