用随机项替换Python字符串

Gab*_*lis 8 python regex string

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

teststr = 'test test test test'
animals = ['bird','monkey','dog','fox']
#replace 'test' with random item from animals
finalstr = ['dog fox dog monkey']
Run Code Online (Sandbox Code Playgroud)

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

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']
Run Code Online (Sandbox Code Playgroud)

它有效,但我相信有一些简单的REGULAR EXPRESSION方法我不熟悉.

unu*_*tbu 10

使用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)
Run Code Online (Sandbox Code Playgroud)

收益率(例如)

bird bird dog monkey
Run Code Online (Sandbox Code Playgroud)

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

  • 不知道谁删了“lambda”版本:`re.sub(r'test', lambda m: random.choice(animals), teststr)` 其实好像更简洁。 (2认同)