Replace first occurrence of string in Python

PythonRegex

Python Problem Overview


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, '')

Python Solutions


Solution 1 - Python

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'

Solution 2 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmarks34View Question on Stackoverflow
Solution 1 - PythonvirhiloView Answer on Stackoverflow
Solution 2 - PythonKonrad RudolphView Answer on Stackoverflow