9

Python中的字符串替换并不难,但我想做一些特别的事情:

teststr = 'test test test test'
animals = ['bird','monkey','dog','fox']
#replace 'test' with random item from animals
finalstr = ['dog fox dog monkey']

我写了一个非常低效的版本:

from random import choice
import string
import re

teststr = 'test test test test'
animals = ['bird','monkey','dog','fox']

indexes = [m.start() for m in re.finditer('test', 'test test test test')]
#indexes = [0, 5, 10, 15]
for i in indexes:
    string.replace(teststr, 'test', choice(animals), 1)

#Final result is four random animals
#maybe ['dog fox dog monkey']

它有效,但我相信有一些我不熟悉的正则表达式的简单方法。

4

3 回答 3

11

使用re.sub 回调

import re
import random

animals = ['bird','monkey','dog','fox']

def callback(matchobj):
    return random.choice(animals)

teststr = 'test test test test'
ret = re.sub(r'test', callback, teststr)
print(ret)

产量(例如)

bird bird dog monkey

的第二个参数re.sub可以是字符串或函数(即回调)。如果它是一个函数,它会在正则表达式模式的每个非重叠出现时调用,并且它的返回值被替换为匹配的字符串。

于 2012-09-16T18:42:39.677 回答
1

您可以使用re.sub

>>> from random import choice
>>> import re
>>> teststr = 'test test test test'
>>> animals = ['bird','monkey','dog','fox']
>>> re.sub('test', lambda m: choice(animals), teststr)
'fox monkey bird dog'
>>> re.sub('test', lambda m: choice(animals), teststr)
'fox dog dog bird'
>>> re.sub('test', lambda m: choice(animals), teststr)
'monkey bird monkey monkey'
于 2012-09-16T18:44:11.443 回答
1

这将完成这项工作:

import random, re
def rand_replacement(string, to_be_replaced, items):
    return re.sub(to_be_replaced, lambda x: random.choice(items), string )
于 2012-09-16T19:05:21.887 回答