Python regex sub,带有以下1个参数

时间:2014-08-26 16:20:01

标签: python regex

我将如何改变......

"Take dog1 and dog5 to the dog kennel"

"Take animal_1 and animal_5 to the dog kennel"

?所以我只想用“animal_”代替“dog”,如果“dog”之后有一个数字。 欢迎任何帮助。

3 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

import re

old_sting = 'Take dog1 and dog5 to the dog kennel'

dog_finder = re.compile(r'dog(\d+)')
new_string = re.sub(dog_finder, lambda dog: 'animal_' + dog.group(1), old_sting)

答案 1 :(得分:1)

这样的事情:

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

这就像我在本地机器上测试一样。它基本上与lambda相同......我只是一只老熊,我认为这更具可读性。

答案 2 :(得分:1)

您可以尝试以下re.sub功能,

>>> 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'

通过前瞻,

>>> m = re.sub(r'dog(?=\d)', r'animal_', s)
>>> m
'Take animal_1 and animal_5 to the dog kennel'