Python Forum
String index out of range
Thread Rating:
  • 2 Vote(s) - 1.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
String index out of range
#1
Hello,
I just started learning to code and I was doing my homework, I ran into an error.
The error is saying this:

Traceback (most recent call last):
File "/Users/daphne/Desktop/School Stuff/Computer science/IntroProg/Project/test3.py", line 8, in <module>
if nom[i] == char:
IndexError: string index out of range

I know it is related to my "nom[i]", but I don't know how to fix. If anyone could help me out, I would really appreciate!

Here is my code:
nom = input('Enter a name:')
length = len(nom)
i = 0
nb_e = 0
char = 'e'

while i <= length:
    if nom[i] == char:
        nb_e = nb_e + 1
    i = i + 1
print('Theres', nb_e, 'e')
Reply
#2
Python is 0-indexed. Therefore the maximum index of a string is the length of the string minus one. Your loop goes all the way to length, thus going out of range. This is one reason to avoid looping over indexes. Loop directly over the string:

for letter in nom:
   if letter == char:
       ...
Also, you should use more descriptive variable names. It makes your code easier to read and understand, like to the people you want help from.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Thank you so much for the explanation!
Yes, also I will make sure next time my names are clearer so people can understand better my code, sorry about that! Smile
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to fix list index out of range longmen 26 5,851 Apr-27-2022, 05:46 PM
Last Post: deanhystad
  list index out of range OliverG 3 2,322 Sep-03-2021, 12:04 AM
Last Post: itsmycode
  List index out of range when turning CSV into dict ranbarr 15 6,388 May-12-2021, 10:38 AM
Last Post: ranbarr
  Use range to add char. to empty string johneven 5 13,807 Mar-24-2020, 11:52 AM
Last Post: mbharatkumar
  list index out of range mcgrim 2 2,896 May-25-2019, 07:44 PM
Last Post: mcgrim
  IndexError: list index out of range abdullahali 4 3,841 Jan-17-2019, 07:54 AM
Last Post: buran
  Accessing data in zip - Index out of range pythoneer 24 12,710 Mar-15-2018, 06:19 PM
Last Post: buran
  "List index out of range" for output values pegn305 3 5,289 Nov-26-2017, 02:20 PM
Last Post: heiner55
  list index out of range DrPengin 1 3,680 Nov-09-2017, 08:35 PM
Last Post: gruntfutuk
  string index out of range cusick11 9 15,082 Mar-03-2017, 11:45 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020