0

I have a string "word ***.** word". And I want to replace the '***.**' with '[\d][\d][\d].[\d]+'. Unable to do it using regex as it's giving key error for '\d'. My code is:

text = 'word ***.** word'
updated_text = re.sub(re.compile(r'\b\*\*\*\b', re.I), '[\d][\d][\d]', text)

I'm getting this error:

Traceback (most recent call last):
  File "/usr/lib/python3.8/sre_parse.py", line 1039, in parse_template
this = chr(ESCAPES[this][1])
KeyError: '\\d'

I know that my code is not correct. But I can't think of any different way. Didn't find anything in the community blogs, as well.

1
  • 2
    Use a raw string and double escape the backslash updated_text = re.sub(re.compile(r'\b\*\*\*\b', re.I), r'[\\d][\\d][\\d]', text) Commented Jun 17, 2021 at 7:50

1 Answer 1

1

This should do the trick:

import re

text = 'word ***.** word'
updated_text = re.sub(re.compile(r'\*', re.I), r'[\\d]', text)
print(updated_text)
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, it did. I had tried double slashes but missed the r. So, it wasn't working. Thanks.

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.