简体   繁体   中英

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']"

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']"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM