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

Question:

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

"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.

Answers:

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
Answered By: Andrej Kesely

The old way would be to use a basic for loop:

string = "USER USER some words USER USER USER words"
substring = "USER"

newstring = []
s_old = ""
for s in string.split(" "):
    if (s!=s_old) or (s!=substring):
        newstring.append(s)
    s_old = s

print(" ".join(newstring))
Answered By: knurzl
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.