franchyze923
franchyze923

Reputation: 1200

Python regex error with tuple. Works with list. Bad escape (end of pattern)

I have a list inside a dictionary that holds regex expressions and the program runs as expected. However, when I turn the list into a tuple I get error bad escape (end of pattern) at position 0.

The below gives the error.

import re

phone_num = '660-349-6829'

dict20 = {"phone": (r'\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4}')}

for k in dict20["phone"]:
    print(k)
    results = re.findall(k, phone_num)
    print(results)


self.string, len(self.string) - 1) from None
sre_constants.error: bad escape (end of pattern) at position 0

This works fine (note list instead of tuple).

import re

phone_num = '660-349-6829'

dict20 = {"phone": [r'\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4}']}

for k in dict20["phone"]:
    print(k)
    results = re.findall(k, phone_num)
    print(results)

Upvotes: 0

Views: 1396

Answers (1)

vbar
vbar

Reputation: 251

That's not a tuple - just parentheses. You have to add a comma before ')' to make it a tuple.

Upvotes: 2

Related Questions