Search code examples
python-re

Come up with the regular expression the matches all the digits in the string "Arizona: 479, 501, 870. California: 209, 213, 650."


I was trying to get the digits from the following code:

import re
fetch_code = re.findall([0-5][0-9], "Arizona: 479, 501, 870. California: 209, 213, 650.")
print(fetch_code)

but got this error: IndexError: list index out of range


Solution

  • The problem seems to be that your call to findall is malformed.

    Inside the call you use this parameters (pattern, string, (and optional) flags=0)

    This return all non-overlapping matches of pattern in the string specified.

    If there are no groups, return a list of strings matching the whole pattern. If there is exactly one group, return a list of strings matching that group. If multiple groups are present, return a list of tuples of strings matching the groups.

    In your specific case, forming the call adecuately would be:

    fetch_code = re.findall(r'[0-5][0-9]', "Arizona: 479, 501, 870. California: 209, 213, 650.")
    

    This returns a list of strings and, based on your regular expression, only numbers between 00 and 59:

    ['47', '50', '20', '21', '50']
    

    I don't know if that is the output that you expected but, anyway, it gives no errors and it is formed with the right syntax.

    I also recommend you to take a look to re documentation.

    Have a noice day!