", -6ren">
gpt4 book ai didi

python - 一次替换字符串中的所有字符

转载 作者:太空宇宙 更新时间:2023-11-04 09:54:07 24 4
gpt4 key购买 nike

我试图通过将字符串拆分为列表并对其进行迭代来替换字符串中的字符。

我已经为所有需要用值替换的键创建了一个字典。

dicta = {
"eq" : "=",
"gt" : ">",
"lt" : "<"
}

s = "name eq 'alex' and age gt 36"
[s.replace(char, dicta.get(char)) for char in s.split(" ") if char in dicta ]

上面的解决方案给了我输出:

["name = 'alex' and age gt 36", "name eq 'alex' and age > 36"]

这是因为我在更改一个字符后创建了整个字符串。

预期输出: ["name = 'alex' and age > 36"]

如何在一次运行中完成?

最佳答案

正则表达式解决方案:(这也将替换在 equality 中的 eq 等其他词中找到的键将被替换:=quality)

import re

dicta = {
"eq" : "=",
"gt" : ">",
"lt" : "<"
}

s = "name eq 'alex' and age gt 36 equality"

# pattern that matches every key in dicta with white space around it
pattern = '|'.join(dicta.keys())

ans = re.sub(pattern, lambda x : dicta.get(x.group(0)), s)

print(ans)

编辑:这是一种拆分和连接方法:(这将用单个空格替换单词之间的多个空格)

dicta = {
"eq" : "=",
"gt" : ">",
"lt" : "<"
}

s = "name eq 'alex' and age gt 36 equality"
ans = ' '.join([dicta.get(word, word)for word in s.split()])

print(ans)

关于python - 一次替换字符串中的所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46598814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com