0

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)

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

That was it! Thank you, that explains why my other tuples were working (they had more than 1 value in).
So your description "when I turn the list into a tuple " is less general than it appears. Next time, please add the information, that the behaviour changes, when the tuple contains more than one element.
Agreed needs more description, however I didn't notice that the behavior was changing based on the tuple size when I asked this question. I thought it was something with that particular regex expression.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.