Replace first occurrence only of a string?

PythonStringReplace

Python Problem Overview


I have something like this:

text = 'This text is very very long.'
replace_words = ['very','word']

for word in replace_words:
    text = text.replace('very','not very')

I would like to only replace the first 'very' or choose which 'very' gets overwritten. I'm doing this on much larger amounts of text so I want to control how duplicate words are being replaced.

Python Solutions


Solution 1 - Python

text = text.replace("very", "not very", 1)

>>> help(str.replace)
Help on method_descriptor:

replace(...)
    S.replace (old, new[, count]) -> string
    
    Return a copy of string S with all occurrences of substring
    old replaced by new.  If the optional argument count is
    given, only the first count occurrences are replaced.

Solution 2 - Python

text = text.replace("very", "not very", 1)

The third parameter is the maximum number of occurrences that you want to replace.
From the documentation for Python:

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

Solution 3 - Python

From http://docs.python.org/release/2.5.2/lib/string-methods.html :

> replace( old, new[, count])
> Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the > first count occurrences are replaced.

I didn't try but I believe it works

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
Questionjblu09View Question on Stackoverflow
Solution 1 - PythonFred NurkView Answer on Stackoverflow
Solution 2 - PythonHassan RazaView Answer on Stackoverflow
Solution 3 - PythonsergiolView Answer on Stackoverflow