List index out of range using re

Viewed 71

While running my program, the program will randomly crash and displayer Error: List index out of range. however, I'm only looking to index the only number in the list. I don't understand why after a certain amount of time this number would cease to exist.

etherPrice = str(cryptocompare.get_price('ETH', currency='USD'))
intRegex2 = re.compile(r'\d+\.\d+')
result2 = intRegex2.findall(etherPrice)
resultString2 = str(result2[0])
1 Answers

The list is empty, when the list is empty ([]) list[0] will throw an error.

resultString2 = None # initialize the result to None, or "" 

etherPrice = str(cryptocompare.get_price('ETH', currency='USD'))
intRegex2 = re.compile(r'\d+\.\d+')
result2 = intRegex2.findall(etherPrice)

# If the matches list is not empty, then retrieve the first element:
if (result2):        
    resultString2 = str(result2[0])

You can also use if (len(result2) > 0) but that's redundant.

Related