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

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

我写了一个 python 代码,它给出了以下错误 "IndexError: string index out of range"

请告诉我如何解决这个错误。

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。当我将 link 更改为其他任何内容时,它工作得很好

类似

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]

试试这个:

actuallink = 'http://www.exxonmobilperspectives.com'
slashcounter = 0
indexslash = 0
while indexslash < len(actuallink):
    if(actuallink[indexslash] == '/'):
        slashcounter = slashcounter + 1
        print("Slash number {},Index ={}".format(slashcounter,indexslash))
    indexslash = indexslash + 1
    PLink = actuallink[:indexslash - 1]
print("Slashcounter = {}".format(slashcounter))

结果:

Slash number 1,Index =5
Slash number 2,Index =6
Slashcounter = 2