1

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

6
  • 3
    The link you provided doesn't have 3 slashes, so the while loop will not stop incrementing indexslash so it will eventually become too high for the string. Commented Feb 24, 2019 at 19:06
  • 1
    what is the final desired outcome of this? Commented Feb 24, 2019 at 19:10
  • @AvivShai , shouldn't the while loop automatically exit after it has indexed to the last character? Commented Feb 24, 2019 at 19:11
  • 1
    No. It continues until 3 is hit for slashcounter. You need an additional guard that accounts for len(actuallink) Commented Feb 24, 2019 at 19:12
  • @QHarr I want to extract the "http://" part from the link. I have an array of links and this link is one of that Commented Feb 24, 2019 at 19:13

2 Answers 2

1

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

Comments

1

Try this:

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))

The result :

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

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.