krish
krish

Reputation: 59

how to replace a match word with other word in python?

I am new to python, I have an issue with replacing. SO I have a list and a string I want to replace the word of string if it matches the word in the list. I have tried it but I am not getting the excepted output. Like below:-

str = "'hi'+'bikes'-'cars'>=20+'rangers'"
list = [df['hi'],df['bikes'],df['cars'],df['rangers']]

for i in list:
    if i in str:
        z=x.replace(j, i)

But getting a wrong answer Execpted output:

 z = "df['hi']+df['bikes']-df['cars']>=20+df['rangers']"

Upvotes: 0

Views: 49

Answers (1)

Epsi95
Epsi95

Reputation: 9047

If you are sure that the column names are always alphabets then simply use

import re
s =  "'hi'+'bikes'-'cars'>=20+'rangers'"
s2 = re.sub(r"('[A-Za-z]+')", r'df[\1]', s)
"df['hi']+df['bikes']-df['cars']>=20+df['rangers']"

Upvotes: 1

Related Questions