Question

I have a string:

I am Tony not charlie, Hey charlie how's you?

I want to replace the second "Charlie", but not the first one.

Expected String:

I am Tony not charlie, Hey Tony how's you?

I'm using following statement to do this

>>> re.sub(r',\s\w{3}\scharlie\s', ' Tony ', 'I am Tony not charlie, Hey charlie how\'s you\?')
"I am Tony not charlie Tony how's you?"

But it's replacing the more than what I want.

How can I make it replace only the second "Charlie" and nothing else?

Was it helpful?

Solution 2

You need to use grouping here in your expression.

See if this is what you wanted:

>>> re.sub(r'(,\s\w*\s)charlie', r'\1Tony', r"I am Tony not charlie, Hey charlie
 how's you?")
"I am Tony not charlie, Hey Tony how's you?"

OTHER TIPS

Replace the first substring (and everything that follows it) with itself and add a limit =1 to prevent replacing 4th, 6th etc occurrences.

s = "I am Tony not charlie, Hey charlie how's you?"
print re.sub('(charlie.*?)charlie', r'\1Tony', s, 1)

For fixed patterns (not your case) look-behind / ahead assertions could be handy:

re.sub(r'(?<=Hey )charlie','Tony',string)

You can create your own replacement function. You split the input sentence on the word you want to replace and check against the index you want to replace the occurring word for:

def rreplace(s, delimiter, replacement, positions=[1]):
    result = []
    sentences = s.split(delimiter)

    for i, sentence in enumerate(sentences):
        result.append(sentence)

        if not i == len(sentences)-1:
            if i in positions:
                result.append(replacement)
            else:
                result.append(delimiter)

    return "".join(result)

This function allows you to choose which occurrances to replace. The default index to replace is "1", i.e, the second occurrence:

s = "I am Tony not charlie, Hey charlie how's you?"
delimiter = "charlie"
replacement = "Tony"

print rreplace(s, delimiter, replacement) 
# I am Tony not charlie, Hey Tony how's you?

You can also choose multiple replacements by overriding the positions argument:

s = "charlie charlie charlie"
delimiter = "charlie"
replacement = "Tony"

print rreplace(s, delimiter, replacement, [0, 2]) 
# Tony charlie Tony
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top