String replacement in 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']
它有效,但我相信有一些简单的REGULAR EXPRESSION方法,我不熟悉。
答案 0 :(得分:10)
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
的第二个参数可以是字符串或函数(即回调)。如果它是一个函数,则会对正则表达式模式的每个非重叠事件进行调用,并替换其返回值来代替匹配的字符串。
答案 1 :(得分: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'
答案 2 :(得分:1)
这可以胜任:
import random, re
def rand_replacement(string, to_be_replaced, items):
return re.sub(to_be_replaced, lambda x: random.choice(items), string )