The documentation below shows a snippet showing how the regex search method works and confirms that it returns a list.
re.findall(r"\w+ly", text) ['carefully', 'quickly']
However, the following code fragment generates an error outside the bounds ( IndexError: list index out of range ) when trying to access the null element of the list returned by the findall function.
Corresponding code snippet:
population = re.findall(",([0-9]*),",line) x = population[0] thelist.append([city,x])
Why is this happening?
For some background, how this snippet fits into my entire script:
import re thelist = list() with open('Raw.txt','r') as f: for line in f: if line[1].isdigit(): city = re.findall("\"(.*?)\s*\(",line) population = re.findall(",([0-9]*),",line) x = population[0] thelist.append([city,x]) with open('Sorted.txt','w') as g: for item in thelist: string = item[0], ', '.join(map(str, item[1:])) print string
EDIT: Read the comment below to find out why this happened. My quick solution:
if population: x = population[0] thelist.append([city,x])
Louis93
source share