问题: 有一个带条件的字符串,我想随机用其他运算符替换一个运算符。
可能的解决方案:
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()
函数要简单得多(为每个不重叠的模式调用回调replacement函数):
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
关于python - 随机替换字符串的某些部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46970394/