简体   繁体   中英

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'

请注意, replace()可以指定最大计数,因此您可以使用一些技巧:

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM