Python: Regex findall returns a list, why does trying to access the list element [0] return an error? -
taken documentation, next snippet showing how regex method findall works, , confirms homecoming list.
re.findall(r"\w+ly", text) ['carefully', 'quickly']
however next code fragment generates out of bounds error (indexerror: list index out of range
)when trying access zeroth element of list returned findall.
relevant code fragment:
population = re.findall(",([0-9]*),",line) x = population[0] thelist.append([city,x])
why happen?
for more background, here's how fragment fits entire script:
import re thelist = list() open('raw.txt','r') f: 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]) open('sorted.txt','w') g: item in thelist: string = item[0], ', '.join(map(str, item[1:])) print string
edit: read comment below background on why happened. quick prepare was:
if population: x = population[0] thelist.append([city,x])
re.findall
homecoming empty list if there no matches:
>>> re.findall(r'\w+ly', 'this not work') []
python regex
No comments:
Post a Comment