sftea
sftea

Reputation: 3

Replacing Substrings Under Certain Conditions

Here is what I have:

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

And I would like to change it to:

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

Here's what my code looks like:

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")`

But, it is replacing both occurrences of "1x" still.

I have used these two posts to get me to a point where I think what I have should be working, but it is not:

Upvotes: 0

Views: 70

Answers (5)

Mauro Baraldi
Mauro Baraldi

Reputation: 6550

Most of the answers before already do the job. This is a solution, inspired in another answer to this question, but, it can be used with any letter in your string. As described in docs, it's called backreferences

>>> 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

Upvotes: 0

Mr. zero
Mr. zero

Reputation: 243

if you want to replace just "1x" use this example :

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

output : x^3+21x^2+x+6

else if you want to replace any number before "x" use this example :

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

output : x^3+x^2+x+6+x+x+x

Upvotes: 0

Ash Ishh
Ash Ishh

Reputation: 578

If equation has only addition operator:

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

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

Output:

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

If equation has multiple operators:

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)

Output:

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

Note: This is inefficient solution

Upvotes: 1

Haifeng Zhang
Haifeng Zhang

Reputation: 31885

add \b to your pattern 1x for exact match the word 1x other than matching 21x or other words contain 1x

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

print(re.sub(r'\b1x\b', r'x', stem_text))

The result is

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

Read python regex docs

Upvotes: 0

ILostMySpoon
ILostMySpoon

Reputation: 2409

Assuming you are looking to replace all exact occurrences of 1x with x, you can use re.sub

import re

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

re.sub(r'\b1x\b', 'x', stem_text)

\b here means word boundary

Upvotes: 1

Related Questions