在某些条件下替换子字符串

时间:2016-03-30 16:56:30

标签: python

这就是我所拥有的:

stem_text = "x^3+21x^2+1x+6"

我想将其更改为:

stem_text = "x^3+21x^2+x+6"

这是我的代码:

indices = [m.start() for m in re.finditer("1x", stem_text)]
for i in indices:
    if stem_text[i-1] not in ["0","1","2","3","4","5","6","7","8","9"]:
        stem_text = stem_text.replace(stem_text[i:i+2],"x")`

但是,它正在取代" 1x"仍然。

我已经使用这两个帖子让我到了一个我认为我应该工作的地方,但事实并非如此:

5 个答案:

答案 0 :(得分:1)

假设您要将$window.location.href = '/'; 的所有确切匹配项替换为1x,您可以使用x

re.sub

import re stem_text = "x^3+21x^2+1x+6" re.sub(r'\b1x\b', 'x', stem_text) 此处表示word boundary

答案 1 :(得分:1)

如果方程只有加法运算符:

stem_text = "x^3+21x^2+1x+6"

new_string = stem_text.replace('+1x','+x')
print(new_string)

输出:

x^3+21x^2+x+6

如果等式有多个运算符:

stem_text = '1x+1x-1x/1x*1x+10x'
op_list = ['','+','-','*','/']
#list of operations in equation
for each_op in op_list:
    stem_text = stem_text.replace(each_op+'1x',each_op+'x') #'each_op + 1x' is used to prevent replacing nos. like 21x,31x etc


print(stem_text)

输出:

x+x-x/x*x+10x

注意:这是效率低下的解决方案

答案 2 :(得分:0)

将\ b添加到您的模式21x以完全匹配单词1x而不是匹配1x或其他单词包含import re stem_text = "x^3+21x^2+1x+6" print(re.sub(r'\b1x\b', r'x', stem_text))

x^3+21x^2+x+6

结果是

webform

阅读python正则表达式docs

答案 3 :(得分:0)

如果您只想替换“1x”,请使用此示例:

stem_text = "x^3+21x^2+1x+6"
indices = [x for x in stem_text.split("+")]
for i in indices:
    if len(i) == 2 and i == "1x": stem_text = stem_text.replace(i + "+", "x+")

print stem_text

输出:x^3+21x^2+x+6

否则,如果您想在“x”之前替换任何数字,请使用此示例:

stem_text = "x^3+21x^2+1x+6+2x+4x+0x"
indices = [x for x in stem_text.split("+")]
Int = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
for x in indices:
    for i in Int:
        if x == i + "x": stem_text = stem_text.replace(i + "x", "x")

print stem_text

输出:x^3+x^2+x+6+x+x+x

答案 4 :(得分:0)

之前的大多数答案已经完成了工作。这是一个解决方案,受到这个问题的另一个答案的启发,但是,它可以与字符串中的任何字母一起使用。如docs中所述,它被称为反向引用

>>> import re
>>> regex = r'\b1(\w)\b'
>>> print(re.sub(regex, r'\g<1>', 'z^3+4z^2+1z+5'))
z^3+4z^2+z+5
>>> print(re.sub(regex, r'\g<1>', 'y^3+21y^2+1y+6'))
y^3+21y^2+y+6