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:
JavaScript
x
2
1
self.phoneRegex = re.compile(r'(+d) ((ddd)) (ddd)(dddd)')
2
Here is the code causing the issues:
JavaScript
1
8
1
for cell in self.cells:
2
if '+1' in cell.text:
3
print(self.pmo.groups()) #Works fine
4
print("{} {} {}-{}".format(self.pmo.groups())) #Errors out.
5
print("{} {} {}-{}".format(self.pmo.group(1), self.pmo.group(2),self.pmo.group(3), self.pmo.group(4))) #Also errors out.
6
if isinstance(self.cursor(row=self.data['lst_row'], column=self.telCol).value, type(None)):
7
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)))
8
Full Traceback:
JavaScript
1
5
1
Traceback (most recent call last):
2
File "F:DocumentsProgramsPythonE45 Contact Info Pullermain.py", line 289, in run
3
print("{} {} {}-{}".format(self.pmo.groups()))
4
IndexError: Replacement index 1 out of range for positional args tuple
5
Advertisement
Answer
You have this string.format
line:
JavaScript
1
2
1
print("{} {} {}-{}".format(self.pmo.groups()))
2
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()
.
JavaScript
1
2
1
print("{} {} {}-{}".format(*self.pmo.groups()))
2