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']
它有效,但我相信有一些我不熟悉的正则表达式的简单方法。