Suppose I have this string:
s = "blah blah blah"
Using Python regex, how can I replace each instance of "blah" with a different value (e.g. I have a list of values v = ("1", "2", "3")
So in your case, you could make a dict trans = {"a": "aa", "b": "bb"} and then pass it into multiple_replace along with the text you want translated. Basically all that function is doing is creating one huge regex containing all of your regexes to translate, then when one is found, passing a lambda function to regex.
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.
The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.
sub() function belongs to the Regular Expressions ( re ) module in Python. It returns a string where all matching occurrences of the specified pattern are replaced by the replace string. To use this function, we need to import the re module first. import re.
You could use a re.sub
callback:
import re
def callback(match):
return next(callback.v)
callback.v=iter(('1','2','3'))
s = "blah blah blah"
print(re.sub(r'blah',callback,s))
yields
1 2 3
You could use re.sub
, which takes a string or function and applies it to each match:
>>> re.sub('blah', lambda m, i=iter('123'): next(i), 'blah blah blah')
<<< '1 2 3'
In this case, you don't need regex:
s.replace("blah","%s")%v
the replace produces "%s %s %s", then you use the format operator
I think you don't really need a regex.
for x in v:
s = s.replace('blah', x, 1)
However if you really wanted a regex:
import re
for x in v:
s = re.sub('blah', x, s, count=1)
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