问题:
有条件字符串,我想将一个运算符随机替换为其他运算符。

可能的解决方案:

import re
import random

s = 'operand1 > 273 and operand2 < 459 or operand3 == 42 and operand4 < 100'

# create list of operators with random replacement
repl = random.choice(['<','>','==','!='])
operators = re.findall(r'[<>]|==|!=', s)
operators[random.choice(range(len(operators)))] = repl

# create list of other parts of the string
the_rest = re.split(r'[<>]|==|!=', s)

# recombine a string
s_new = the_rest[0]
for operator, operand in zip(operators, the_rest[1:]):
    s_new += operator + operand
print(s_new)


似乎有点模糊。您能提供一种更好的方法吗?

谢谢。

最佳答案

使用re.sub()函数要简单得多(对于模式的每个非重叠出现,都会使用回调替换函数):

import random, re

s = 'operand1 > 273 and operand2 < 459 or operand3 == 42 and operand4 < 100'
operators = ['<','>','==','!=']
s_new = re.sub(r'[<>]|==|!=', lambda op: random.choice(operators), s)

print(s_new)


示例输出:

operand1 != 273 and operand2 == 459 or operand3 > 42 and operand4 == 100


https://docs.python.org/3/library/re.html?highlight=re#re.sub

09-17 03:40