Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace first occurrence of string in Python

Tags:

python

regex

People also ask

How do I change the first occurrence of a string in Python?

If we want to replace only the first occurrences of a substring in a string with another character or sub-string, then we need to pass the count argument as 1 in the replace() function, sample_str = "This is a sample string, where is need to be replaced."

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 remove the first occurrence of 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 I change the first occurrence of a list in Python?

A string is immutable in Python, therefore the replace() function returns a copy of the string with modified content. To replace only first occurrence of “is” with “XX”, pass the count value as 1. For example: strValue = "This is the last rain of Season and Jack is here."


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'

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