String index out of range python как исправить

I have had a look at a lot of previous questions put up, but still couldn't find anything that'll help me here. Here's a code I wrote to Reverse a sentence. I could have used split() function, but I

I have had a look at a lot of previous questions put up, but still couldn’t find anything that’ll help me here.
Here’s a code I wrote to Reverse a sentence.
I could have used split() function, but I tried to do without it anyways.

s='abcdef ghij klmn op qrst uv w xy z'
s=s[::-1]
print s
j=0
p=''
while(j<len(s)):
    a=''
    while(s[j]!=''):
        a=a+s[j]
        j+=1
    p.append(a[::-1])
    j+=1
print p

It gives me a string index out of range error in the while bracket. Why?

Thanks a lot for the help.

asked Oct 1, 2012 at 17:23

Chocolava's user avatar

3

Because in the second while loop you’re incrementing j without checking if you’re at the end yet.

Also, s[j]!='' will always be true for strings. If you can use the index operator on a string it means that there are characters. Otherwise there are none.

For example:

s = ''
s[0]  # IndexError, there are no characters so there can be no index

s = 'x'
s[0]  # Will be x and s[1] will give the same error as above

A little simpler version of your code (not really Pythonic, would be nicer to use lists and use ' '.join()):

s = 'abcdef ghij klmn op qrst uv w xy z'
print s

p = ''
i = 0
word = ''
while i < len(s):
    c = s[i]
    if c == ' ':
        if p:
            p = word + ' ' + p
        else:
            p = word

        word = ''
    else:
        word += c
    i += 1

print p

And the clean/simple Pythonic version with split:

s = 'abcdef ghij klmn op qrst uv w xy z'
print s
p = ' '.join(s.split()[::-1])
print p

answered Oct 1, 2012 at 17:26

Wolph's user avatar

WolphWolph

77.1k11 gold badges136 silver badges148 bronze badges

0

Your issue is with this inner loop:

while(s[j]!=''):
    a=a+s[j]
    j+=1

This loop allows j to exceed the length of s, you probably want to add an additional condition here to prevent this (I also removed the unnecessary parentheses):

while j < len(s) and s[j] != '':
    a=a+s[j]
    j+=1

answered Oct 1, 2012 at 17:28

Andrew Clark's user avatar

Andrew ClarkAndrew Clark

199k33 gold badges270 silver badges300 bronze badges

1

I think you want to do this: —

s='abcdef ghij klmn op qrst uv w xy z'
s=s[::-1]
print s
j=0
p=[]
while(j<len(s)):
    a=''
    while(j<len(s) and s[j]!=' '):
        a=a+s[j]
        j+=1
    p.append(a[::-1])
    j+=1
print ' '.join(p)

answered Oct 1, 2012 at 17:36

Ashwani Kumar's user avatar

1

while(s[j]!=''):
        a=a+s[j]
        j+=1

Here’s is the problem.. Your last character is z.. When it reaches there, your while condition is true.. And it tries increment j to next index.. Which is out of bound..

You can probably move this condition also to your outer while loop.. Because you need to check both the conditions at the same time… Both the conditions must be true in your case..

answered Oct 1, 2012 at 17:27

Rohit Jain's user avatar

Rohit JainRohit Jain

207k45 gold badges405 silver badges518 bronze badges

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
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!

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]

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 tutorial, we will discuss how to handle string index out of range error. Before moving ahead, let’s first understand what is string index out of range error is in Python.

Just like lists, strings are also indexed in Python. We can define a string as a set of Unicode characters stored inside. In simpler terms, you can access each item in a string using its index value which starts with zero. So the first character index is 0, and the last character index is equal to the length of the string-1.

Whenever you try to access an item whose index value does not exist in the string, an error is thrown by the Python interpreter known as string index out of range.

Also Read: Python For Loop Index With Examples

Let us consider a string: Codeitbro. In this string, the index of C is 0, and the index of o is 8 (as the length of the string is 9).

When accessing the characters inside a string, we can use their index values to access them. However, if you use an index not available in the string, you will get the index out of range error.

As in the above example, the index range is only up to 8. but if we try to access it using an index value of 10, we will get the error.

Let’s see the error in the below code to get a value at the 10th index position.

#consider a string
my_string = "Codeitbro"

#get the tenth charcater
print(my_string[9])

Error:

index out of range error in python

IndexError                                Traceback (most recent call last)
<ipython-input-22-5d6870b88bcc> in <module>()
      3 
      4 #get the tenth charcater
----> 5 print( my_string[9])
      6 

IndexError: string index out of range

Also Read: How to Reverse an Array In Python [Flip Array]

How to Handle String Index Out of Range Error In Python

To handle this error, we will see the following methods.

Method 1: Use the relevant index

We have to use the index of a character in the string only. To get the character by indexing from the string, you can use [].

Syntax:

my_string[index]

Where,

1. my_string is the input string.

2. index is the character index in the string that is present.

Also Read: How to Check If Dict Has Key in Python [5 Methods]

Example:

We will create a string and get the character using an index in this example.

#consider a string
my_string = "Codeitbro"

#get the first charcater
print( my_string[0])

#get the fifth charcater
print( my_string[4])

#get the second charcater
print( my_string[3])

#get the last charcater
print( my_string[8])

Output:

C
i
e
o

Also Read: How to Convert Binary to Decimal in Python [5 Methods]

Method 2: Using Exception Handling to Handle String Index Out of Range Error

We will use the exception handling concept to handle the error in this scenario. For this, we will use try and except code blocks.

Here’s the syntax:

try:
  statements

except IndexError:
  handling

In the try block, we will use statements to retrieve a value based on an index value in the string. If there is no error, it will return the character. Otherwise, Python will execute the statements in the except block to handle the error.

Also Read: Python Program To Display Fibonacci Series Up To N Terms

Let’s see a few examples to understand this more coherently.

Example 1: In this example, we will create a string and try to get the tenth character using index and display an error message if there is any string index out of range error under the except block.

Code:

#consider a string
my_string = "Codeitbro"

try:
  #get the tenth charcater
  print( my_string[9])

except IndexError:
  print("Index error occured")

Output:

Index error occured

Also Read: How To Automate Google Search With Python

Example 2: We will create a string and get the seventh character using the index in this example.

#consider a string
my_string = "Codeitbro"

try:
  #get the seventh charcater
  print( my_string[6])

except IndexError:
  print("Index error occured")

There is no error found in the try block of the above code, and therefore it prints the sixth character of the string, i.e., “b.”

Output:

b

Also Read: 10 Best Udemy Python Courses for Beginners

Wrapping Up

In this tutorial, we explored two methods to handle string index out of range error in Python. The first is pretty straightforward, in which you have to use the correct index to get a value from the string. The second method is robust as it uses the exception handling concept to handle the index out of range error.

Next Reads:

  • Learn Python Online With These 12 Best Free Websites
  • 7 Best Python IDE for Windows [Code Editors]
  • 11 Best Python Libraries for Machine Learning
  • How To Make A Simple Python 3 Calculator Using Functions
  • How To Create Keylogger In Python
  • How To Make A Digital Clock In Python Using Tkinter
  • Working With Python 3 Lists | Learn By Examples
  • Dictionary In Python 3 | Learn With Examples

Понравилась статья? Поделить с друзьями:
  • Street power football не удалось подключиться к сети как исправить
  • Stream write error перевод как исправить
  • Stream write error stalker anomaly
  • Storehouse как изменить комплект
  • Stop error 0x0000001e