Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all except the first occurrence of a substring in Python?

Tags:

python

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

like image 205
Souvik Ray Avatar asked Oct 12 '19 11:10

Souvik Ray


People also ask

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

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.

How do you replace all instances of substring in Python?

The easiest way to replace all occurrences of a given substring in a string is to use the replace() function.

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


1 Answers

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
like image 54
RomanPerekhrest Avatar answered Nov 14 '22 23:11

RomanPerekhrest