gpt4 book ai didi

用随机项替换 Python 字符串

转载 作者:太空狗 更新时间:2023-10-29 20:50:22 27 4
gpt4 key购买 nike

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 的简单方法。

最佳答案

使用 re.sub callback :

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

关于用随机项替换 Python 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12449555/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com