marks34
marks34

Reputation: 2107

Replace first occurrence of string in Python

I have some sample string. How can I replace first occurrence of this string in a longer string with empty string?

regex = re.compile('text')
match = regex.match(url)
if match:
    url = url.replace(regex, '')

Upvotes: 186

Views: 209973

Answers (2)

virhilo
virhilo

Reputation: 6793

string replace() function perfectly solves this problem:

string.replace(s, old, new[, maxreplace])

Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'

Upvotes: 376

Konrad Rudolph
Konrad Rudolph

Reputation: 546123

Use re.sub directly, this allows you to specify a count:

regex.sub('', url, 1)

(Note that the order of arguments is replacement, original not the opposite, as might be suspected.)

Upvotes: 27

Related Questions