learner
learner

Reputation: 2752

How to delete all occurences of a substring except the first one in any string

Given a string text and a proper substring query. How to delete all occurence of the query except the first one?

Example:

text = 'cccsumoxxxsumoppqqsumovvvvsumo' 
query = 'sumo' 

result: 'cccsumoxxxppqqvvvv'

Upvotes: 1

Views: 824

Answers (4)

Jon Clements
Jon Clements

Reputation: 142256

I'd use str.partition:

def f(text, qry):
    pre, sep, suf = text.partition(qry)
    return pre + sep + suf.replace(qry, '')

This transparently handles cases where the query string may or may not exist and does the minimum necessary processing of the string (no counting of the query string or slicing etc...)

Upvotes: 4

Austin
Austin

Reputation: 26057

A simple way to do is using slicing.

text = 'cccsumoxxxsumoppqqsumovvvvsumo' 
query = 'sumo' 
first = text.index(query) + len(query)
text = text[:first] + text[first:].replace(query, "")
print(text)

Output:

cccsumoxxxppqqvvvv

Upvotes: 0

Omar Einea
Omar Einea

Reputation: 2524

A simpler way to do it:

''.join(text.rsplit(query, text.count(query) - 1))

This reverse splits text where query is found (thus removing it), except the last occurrence (hence -1), and then joins all split pieces.

Upvotes: 1

llllllllll
llllllllll

Reputation: 16434

Notice that replace() can specify a max count, thus you can exploit it with a little trick:

text[::-1].replace(query[::-1], '', text.count(query)-1)[::-1]

Upvotes: 6

Related Questions