SKK
SKK

Reputation: 31

Python, string is returning IndexError: list index out of range

get_code="https://localhost:8080/soieurow/KPP/alksdjfhlkjhekajhf?eowuiro=akleireyi&URL=https%3A%2F%2Flocalhost:8080%2Fmga%2Fsps%2Foauth%2Foauth20%2Fauthorize%3Fresponse_type%3Dcode%26scope%3Dopenid%2Bname%2Bemail%2Bpostal_code%26client_id%3Dthaljlwej%26redirect_uri%3Dhttp%3A%2F%2Faklsdjfhwekdisd.com%3A5006%2Fredirectcode%26nonce%3DQJT8RbymFk%26acrakdjasd%3DD1%26token%3DfkasjfhalskfhlaksjhkL61bqqADtekpH-HE55lZaX2LJH4Ii9diraseufhalksfhl%26correlation_id%3D4102479872341%26support_encryption%3Dsj2aljkadfj3%26state%3Dajk1234"
code='code'
if code in get_code:
    code=get_code.split("code=")[1][:47]
    print("i havce code",code)
else:
    print("i don't find code")

I am passing string, but i am getting IndexError: list index out of range

Upvotes: 0

Views: 383

Answers (2)

balderman
balderman

Reputation: 23815

Your bug is that you asked if 'code' is in the string but you split by 'code='. Fix that and the code will work as expected.

Upvotes: 1

Emran
Emran

Reputation: 621

The index error is about the first one ([1]) not the second one ([:47]). It's because the get_code string doesn't contain any code= string at all!
So here is what happens:

  • split method returns the list of substrings split by code=; which in turn doesn't find any code= and returns the whole get_code string as an array of length 1. (i.e returns ["https://..."])
  • But you wanted to get the second element of the returned array (as of [1] part) which leads to an error since the array has only one element at the index of 0!

Upvotes: 1

Related Questions