Remove adjacent duplicate words in a string with Python?

How would I remove adjacent duplicate words in a string. For example 'Hey there There' -> 'Hey there'


Submitted July 22nd 2021 by Admin


Using re.sub with a backreference we can try:

inp = 'Hey there There'
output = re.sub(r'(\w+) \1', r'\1', inp, flags=re.IGNORECASE)
print(output) # Hey there

The regex pattern used here says to:

(\w+) match and capture a word
[ ] followed by a space
\1 then followed by the same word (ignoring case)

Then, we just replace with the first adjacent word.

Admin | 3 days ago

Relevant Questions