Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

(Python) How do I remove all adjacent substrings in a string and keep only the first occurrence?

I’ve seen similar questions to this but unfortunately I couldn’t find the exact case for my problem. What I was looking to do is remove all adjacent occurrences of a set substring but keep the first occurrence.

For example, given

s = "USER USER some words USER USER USER words"
substring = "USER"

The output I want would be

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"USER some words USER words"

I’ve tried using sub(), split() but I couldn’t find the answer I wanted. Would appreciate any help, thank you.

>Solution :

Try re:

import re

s = "USER USER some words USER USER USER words"
substring = "USER"

s = re.sub(fr"({re.escape(substring)})(\s+\1)+", substring, s)
print(s)

Prints:

USER some words USER words
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading