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.6k3 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 badges604 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.2k29 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]
Время чтения 4 мин.
Строки Python — это массивы байтов, представляющие символы Unicode. Однако в Python нет символьного типа данных, и один символ — это просто строка длиной 1.
В этом руководстве мы увидим, как получить доступ к символам в строке по индексу в Python. Python предоставляет богатый набор операторов, функций и методов для работы со строками.
Содержание
- Индексация строк в Python
- Доступ к символам строки по индексу
- IndexError: индекс строки вне допустимого диапазона
- TypeError: строковые индексы должны быть целыми числами
- Доступ к строковым символам по отрицательному индексу
- Изменение символов в строке с помощью []
- Нарезка строк в Python
- Заключение
Часто в языках программирования к отдельным элементам в упорядоченном наборе данных можно обращаться напрямую, используя числовой индекс или значение ключа. Этот процесс называется индексацией.
В Python строки представляют собой упорядоченные последовательности символьных данных и, следовательно, могут быть проиндексированы таким образом. Доступ к отдельным символам в строке можно получить, указав имя строки, за которым следует число в квадратных скобках([]).
Доступ к символам строки по индексу
Индексация строк в Python начинается с нуля: первый символ в строке имеет индекс 0, следующий — индекс 1 и так далее.
Индексом последнего символа будет длина строки — 1.
См. следующий пример.
# app.py str = ‘Millie Bobby Brown’ print(str[7]) |
Так как в Python индексация строк начинается с 0 до n-1, где n — размер строки, символы в строке размера n доступны от 0 до n-1.
В приведенном выше коде мы обращаемся к символу по индексу.
Индекс начинается с 0, поэтому мы выберем 7-й символ, то есть B.
Выход:
➜ pyt python3 app.py B ➜ pyt |
Мы можем получить доступ к отдельным символам, используя индекс, начинающийся с 0.
IndexError: индекс строки вне допустимого диапазона
Если мы попытаемся использовать индекс за концом строки, это приведет к ошибке.
См. следующий код.
# app.py str = ‘Millie’ print(str[7]) |
Выход:
➜ pyt python3 app.py Traceback(most recent call last): File «app.py», line 2, in <module> print(str[7]) IndexError: string index out of range ➜ pyt |
Итак, мы получили ошибку: IndexError: string index out of range.
TypeError: строковые индексы должны быть целыми числами
Разрешается передавать только целые числа, так как индекс, число с плавающей запятой или другие типы вызовут ошибку TypeError.
См. следующий код.
# app.py str = ‘Emma Watson’ print(str[1.5]) |
Выход:
➜ pyt python3 app.py Traceback(most recent call last): File «app.py», line 2, in <module> print(str[1.5]) TypeError: string indices must be integers ➜ pyt |
Мы передали значение с плавающей запятой в качестве индекса; вот почему мы получили TypeError: строковые индексы должны быть целыми числами.
Доступ к строковым символам по отрицательному индексу
Строковые индексы также могут быть указаны с отрицательными числами, и в этом случае индексирование происходит с конца строки назад:
- строка[-1] относится к последнему символу,
- string[-2] предпоследний символ и так далее.
- Если размер строки равен n, тогда string[-n] вернет первый символ строки.
См. следующий код.
# app.py str = ‘Emma Watson’ print(str[—6]) print(str[—5]) print(str[—len(str)]) |
Выход:
➜ pyt python3 app.py W a E ➜ pyt |
Попытка проиндексировать отрицательные числа за пределами начала строки приводит к ошибке.
Для любой непустой строки str, str[len(s)-1] и str[-1] возвращают последний символ. Нет индекса, который имел бы смысл для пустой строки.
Изменение символов в строке с помощью []
Давайте попробуем изменить строку, назначив определенные символы в определенную позицию.
# app.py str = ‘Emma Watson is Hermione’ str[6] = ‘K’ |
Выход:
➜ pyt python3 app.py Traceback(most recent call last): File «app.py», line 2, in <module> str[6] = ‘K’ TypeError: ‘str’ object does not support item assignment ➜ pyt |
Мы получим TypeError: объект ‘str’ не поддерживает присваивание элемента.
Нарезка строк в Python
Python также допускает форму синтаксиса индексации, которая извлекает подстроки из строки, известную как нарезка строки.
Если str является строкой, выражение формы str[x:y] возвращает часть s, начиная с позиции x и до позиции y, но не включая ее.
Допустим, мы хотим извлечь Watson из строки Emma Watson с помощью среза, а затем мы можем написать следующий код для получения этого вывода.
# app.py str = ‘Emma Watson is Hermione’ print(str[5:11]) |
Выход:
➜ pyt python3 app.py Watson ➜ pyt |
Опять же, второй индекс указывает первый символ, который не включен в результат. Это может показаться несколько неинтуитивным, но дает следующий результат, который имеет смысл: выражение str[x:y] вернет подстроку длиной y – x символов, в данном случае 11 – 5 = 6. Итак, Watson слово из 6 символов.
Строковые индексы отсчитываются от нуля. Первый символ в строке имеет индекс 0. Это относится как к стандартной индексации, так и к нарезке.
Заключение
Символы доступа в String являются базовыми операциями в любом языке программирования, а Python очень легко обеспечивает индексирование и нарезку. Мы можем получить доступ к символам, указав положительный и отрицательный индекс.
“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
When working with Python strings, you might encounter the following error:
IndexError: string index out of range
This error occurs when you attempt to access a character in a string with an index position that’s out of the available range.
This tutorial will show you an example that causes this error and how to solve it in practice.
How to reproduce this error
Every character in a Python string is assigned an index number to mark the position of that character in the string.
The index number starts from 0 and is incremented by 1 for each character in the string.
Suppose you create a string containing ‘Hello’ as follows:
The index numbers of the string are shown in the following illustration:
Following the illustration, this means that the maximum index number is 4 for the character ‘o’:
my_string = "Hello"
print(my_string[4])
print(my_string[5])
Output:
o
Traceback (most recent call last):
File "main.py", line 4, in <module>
print(my_string[5])
IndexError: string index out of range
As you can see, the character ‘o’ is printed when we access the string with 4 as the index position.
When we try to access the character at index 5, the error is raised. This is because there’s no character stored at that index number.
How to fix this error
To resolve this error, you need to avoid accessing the string using an index number that’s greater than the available indices.
One way to do this is to check the index number if it’s less than the length of the string as follows:
my_str = "Hello"
n = 5
if n < len(my_str):
print(my_str[n])
else:
print("Hey! Index out of range")
This code works because the index positions available in a string will always be less than the length of that string.
The len()
function counts the number of characters in a string from 1, while the index starts from 0.
By using an if-else
statement and comparing if the index number you want to use is less than the length, you won’t receive the error.
As an alternative, you can also use a try-except
block as follows:
my_str = "Hello"
try:
print(my_str[9])
except:
print("Hey! Index out of range")
By using a try-except
block, the error will be handled with a print()
statement so that your code execution doesn’t stop.
Conclusion
The IndexError: string index out of range
occurs when the index position you want to access is not reachable. Usually, the index position you specified is greater than or equal to the length of the string itself.
To resolve this error, you need to make sure that you’re using an index number that’s available within the string. You can use an if-else
or try-except
block to do so.
I hope this tutorial is helpful. Happy coding! 👍