如何解决python中的以下错误:“IndexError:string index out of range”

2024-10-03 06:26:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个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]

另外,当我改变链接到其他任何东西,它的作品完美


Tags: of代码comhttpstringindexwww错误
2条回答

试试这个:

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

像这样的

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]

相关问题 更多 >