I have a string in Python, say The quick @red fox jumps over the @lame brown dog.
I'm trying to replace each of the words that begin with @
with the output of a function that takes the word as an argument.
def my_replace(match): return match + str(match.index('e')) #Psuedo-code string = "The quick @red fox jumps over the @lame brown dog." string.replace('@%match', my_replace(match)) # Result "The quick @red2 fox jumps over the @lame4 brown dog."
Is there a clever way to do this?
To replace a string in Python, the regex sub() method is used. It is a built-in Python method in re module that returns replaced string. Don't forget to import the re module. This method searches the pattern in the string and then replace it with a new given expression.
sub() method will replace all pattern occurrences in the target string. By setting the count=1 inside a re. sub() we can replace only the first occurrence of a pattern in the target string with another string. Set the count value to the number of replacements you want to perform.
To perform multiple replacements in each element of string , pass a named vector ( c(pattern1 = replacement1) ) to str_replace_all . Alternatively, pass a function to replacement : it will be called once for each match and its return value will be used to replace the match.
You can pass a function to re.sub
. The function will receive a match object as the argument, use .group()
to extract the match as a string.
>>> def my_replace(match): ... match = match.group() ... return match + str(match.index('e')) ... >>> string = "The quick @red fox jumps over the @lame brown dog." >>> re.sub(r'@\w+', my_replace, string) 'The quick @red2 fox jumps over the @lame4 brown dog.'
I wasn't aware you could pass a function to a re.sub()
either. Riffing on @Janne Karila's answer to solve a problem I had, the approach works for multiple capture groups, too.
import re def my_replace(match): match1 = match.group(1) match2 = match.group(2) match2 = match2.replace('@', '') return u"{0:0.{1}f}".format(float(match1), int(match2)) string = 'The first number is 14.2@1, and the second number is 50.6@4.' result = re.sub(r'([0-9]+.[0-9]+)(@[0-9]+)', my_replace, string) print(result)
Output:
The first number is 14.2, and the second number is 50.6000.
This simple example requires all capture groups be present (no optional groups).
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