4

I need to remove repetitive words in string so that 'the (the)' will become 'the'. Why can't I do it as follows?

re.sub('(.+) \(\1\)', '\1', 'the (the)')

Thanks.

2 Answers 2

6

You need to doubly escape the back-reference:

re.sub('(.+) \(\\1\)', '\\1', 'the (the)')
--> the

Or use the r prefix:

When an "r" or "R" prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string.

re.sub(r'(.+) \(\1\)', r'\1', 'the (the)')
--> the
Sign up to request clarification or add additional context in comments.

1 Comment

@eumiro Yup, I just had to find a link to the relevant documentation :)
2

According to documentation: 'Raw string notation (r"text") keeps regular expressions sane.'

Comments

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.