0

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.

4
  • Are you trying to remove // comments starter from the start of the string? Commented May 18, 2015 at 6:01
  • What is the input you are passing to the function while running the program ? Commented May 18, 2015 at 6:02
  • Remove the i=1 line; also, what problem are you trying to solve with this function? Commented May 18, 2015 at 6:07
  • Condition should be i+1==len(string), not i==len(string), because python indicies are zero-based Commented May 18, 2015 at 6:09

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.