Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 765
jblu09 Avatar asked May 15 '11 01:05

jblu09


People also ask

How do you replace only one occurrence of a string in Python?

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

How do you replace only one occurrence of a string in Java?

To replace the first occurrence of a character in Java, use the replaceFirst() method.

How do I remove the first occurrence of a character from a string in Python?

Using a Loop to remove the first occurrence of character in String. Create an empty string to store our result and a flag set to False to determine whether we have encountered the character that we want to remove. Iterate through each character in the original string.

How do you find the first occurrence of a string?

To find the index of first occurrence of a substring in a string you can use String. indexOf() function. A string, say str2 , can occur in another string, say str1 , n number of times.


1 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. 
like image 77
Fred Nurk Avatar answered Sep 21 '22 09:09

Fred Nurk