Reputation: 47
I coded the python function given below:
def processstring(string):
gtkname=""
if string[0]=="/":
i=1
while(string[i]!="/"):
if i==len(string):
break
gtkname=gtkname+string[i]
i=i+1
return gtkname
return string
when I execute the code it gives me the following error:
while(string[i]!="/"):
IndexError: string index out of range.
I don't know why is it giving this error.
Upvotes: 0
Views: 62
Reputation: 748
You are not manipulating the iteration on string characters in a proper way
def processstring(string):
if string[0]=="/":
return string[1:string.find("/",1)]
return string
Python give us ways to not using direct iteration on index of a list
Upvotes: 0
Reputation: 658
The condition is causing the error: while string[i] != "/":
After you increment i
, you check that condition before you check if i == len(string):
to break the loop. Move that check to the end of the loop:
while(string[i]!="/"):
gtkname=gtkname+string[i]
i=i+1
if i==len(string):
break
Upvotes: 3