簡體   English   中英

如何用 python 中的其他詞替換匹配詞?

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

我是 python 的新手,更換時遇到問題。 所以我有一個列表和一個字符串,如果它與列表中的單詞匹配,我想替換字符串中的單詞。 我試過了,但我沒有得到例外的 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)

但是得到一個錯誤的答案Execpted output:

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

如果您確定列名始終是字母,則只需使用

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