如何解决此“ IndexError:字符串索引超出范围”

时间:2019-02-24 18:58:25

标签: python python-3.x index-error

我写了一个python代码,该代码给我“ IndexError:字符串索引超出范围”。请告诉我如何解决此问题。

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。我不知道为什么,但是当我将链接更改为其他任何链接时,它都能正常工作

2 个答案:

答案 0 :(得分:1)

类似

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]

答案 1 :(得分:1)

尝试一下:

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