Search code examples
pythonpython-3.xindex-error

How to solve the following error in python: "IndexError: string index out of range"


I have written a python code which gives the following error "IndexError: string index out of range"

Please tell me how to fix this error.

actuallink = 'http://www.exxonmobilperspectives.com'
slashcounter = 0
indexslash = 0
while slashcounter < 3:
    if(actuallink[indexslash] == '/'):
        slashcounter = slashcounter + 1
    indexslash = indexslash + 1
    PLink = actuallink[:indexslash - 1]

PS. When I change the link to anything else, it works perfectly


Solution

  • Something like

    actuallink = 'http://www.exxonmobilperspectives.com'
    endPoint = len(actuallink.split('/')) - 1
    if endPoint > 0:
        slashcounter = 0
        indexslash = 0
        while slashcounter < endPoint:
            if(actuallink[indexslash] == '/'):
                slashcounter = slashcounter + 1
            indexslash = indexslash + 1
            PLink = actuallink[:indexslash]