简体   繁体   English

如何用 python 中的其他词替换匹配词?

[英]how to replace a match word with other word in python?

I am new to python, I have an issue with replacing.我是 python 的新手,更换时遇到问题。 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:-我试过了,但我没有得到例外的 output。如下所示:-

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:但是得到一个错误的答案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']"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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