How would I change....
"Take dog1 and dog5 to the dog kennel"
to
"Take animal_1 and animal_5 to the dog kennel"
? So I only want to substitute "animal_" for "dog" if "dog" has a number after it. Any help is welcome.
How would I change....
"Take dog1 and dog5 to the dog kennel"
to
"Take animal_1 and animal_5 to the dog kennel"
? So I only want to substitute "animal_" for "dog" if "dog" has a number after it. Any help is welcome.
You could try the below re.sub function,
>>> import re
>>> s = "Take dog1 and dog5 to the dog kennel"
>>> m = re.sub(r'dog(\d)', r'animal_\1', s)
>>> m
'Take animal_1 and animal_5 to the dog kennel'
Through lookahead,
>>> m = re.sub(r'dog(?=\d)', r'animal_', s)
>>> m
'Take animal_1 and animal_5 to the dog kennel'
Something like this:
>>> import re
>>> def dog_replace(matchobj):
... number = matchobj.group(0)[-1:];
... return "animal_"+ number
>>> re.sub('dog[0-9]', dog_replace, "Take dog1 and dog5 to the dog kennel")
"Take animal_1 and animal_5 to the dog kennel"
This works as I have tested it on my local machine. It is essentially the same as the lambda...i'm just an old bear and I think this is more readable.