Skip to content
Advertisement

Python Regex groups causing index errors

So, my interpereter is complaining about IndexError: Replacement index 1 out of range for positional args tuple when calling re.group(#) or re.groups() under specific circumstances. It is meant to return a phone number, such as +1 (555) 555-5555

Here is the regex used, as it is declared elsewhere:

self.phoneRegex = re.compile(r'(+d) ((ddd)) (ddd)(dddd)')

Here is the code causing the issues:

for cell in self.cells:
    if '+1' in cell.text:
        print(self.pmo.groups()) #Works fine
        print("{} {} {}-{}".format(self.pmo.groups())) #Errors out.
        print("{} {} {}-{}".format(self.pmo.group(1), self.pmo.group(2),self.pmo.group(3), self.pmo.group(4))) #Also errors out.
        if isinstance(self.cursor(row=self.data['lst_row'], column=self.telCol).value, type(None)):
            self.cursor(row=self.data['lst_row'], column=self.telCol).value = "{} {};".format("{} {} {}-{}".format(self.pmo.group(2), self.pmo.group(2),self.pmo.group(3), self.pmo.group(4)))

Full Traceback:

Traceback (most recent call last):
  File "F:DocumentsProgramsPythonE45 Contact Info Pullermain.py", line 289, in run
    print("{} {} {}-{}".format(self.pmo.groups()))
IndexError: Replacement index 1 out of range for positional args tuple

Advertisement

Answer

You have this string.format line:

print("{} {} {}-{}".format(self.pmo.groups())) 

re match groups are tuples, so here, you have 4 format substitutions, but you’re trying to pass a single tuple (that contains 4 matches per your regex) instead of 4 separate argument for formatting.

You need to unpack (or splat) the tuple for the string formatting – notice the * added before self.pmo.groups().

print("{} {} {}-{}".format(*self.pmo.groups())) 
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement