I have a string which looks like below
string = "SELECT sdfdsf SELECT sdrrr SELECT 5445ff"
Now I want to replace every occurrence of SELECT
except the first one with @@@SELECT
so that in the end string looks like this
"SELECT sdfdsf @@@SELECT sdrrr @@@SELECT 5445ff"
Now Python replace()
replaces all occurrence of SELECT.
string = string.replace("SELECT", "@@@SELECT)
So the string becomes
"@@@SELECT sdfdsf @@@SELECT sdrrr @@@SELECT 5445ff"
How do I ensure except the first instance, everything else is replaced?
Note: The string can have n occurrences of SELECT
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. Show activity on this post. The third parameter is the maximum number of occurrences that you want to replace.
The easiest way to replace all occurrences of a given substring in a string is to use the replace() function.
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."
With additional "reversed" substitution step:
s = "SELECT sdfdsf SELECT sdrrr SELECT 5445ff"
res = s.replace("SELECT", "@@@SELECT").replace("@@@SELECT", "SELECT", 1)
print(res)
The output:
SELECT sdfdsf @@@SELECT sdrrr @@@SELECT 5445ff
A more sophisticated, but ensuring target word boundaries, could be as below:
import re
def make_replacer():
rpl = ''
def inner(m):
nonlocal rpl
res = rpl + m.group()
rpl = '@@@'
return res
return inner
s = "SELECT sdfdsf SELECT sdrrr SELECT 5445ff"
res = re.sub(r'\bSELECT\b', make_replacer(), s)
print(res) # SELECT sdfdsf @@@SELECT sdrrr @@@SELECT 5445ff
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