python - 随机替换字符串的某些部分

标签 python regex string replace

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

可能的解决方案:

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/

相关文章:

python - 搜索我的 Pygame 版本

java - 如何使用正则表达式处理字符串

java - Java Web 应用程序中的字符串常量与资源包

python - 如何增加qtablewidget的行高和列宽

python - 在 django 1.7.6 上运行 django-oscar 的 Heroku 上从 Python 2.7 切换到 Python 3.4 时出现导入错误

regex - git 提交中的 SLOC

php - 正则表达式出错

Java随机插入字符串

javascript - 为什么我不能在 reduce 回调的元素上使用 string.charCodeAt()

python - 适用于Docker的Google Cloud日志记录驱动程序不会收集日志