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."
>>> 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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With