Replace First Occurrence Only of a String?

Replace First Occurrence Only of a String?

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.

1

3 Answers

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

From :

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.