有没有更好的方法来替换 python 中的字符串?

Is there a better way to replace a string in python?

我有一个问题需要解决,例如:

s1 = "1$<2d>46<2e>5"

str_dict = {
    "<2c>": ",",
    "<2e>": ".",
    "<2f>": "/",
    "<2d>": "-",
    "<2b>": "+",
    "<3d>": "=",
    "<3f>": "?",
    "<2a>": "*",
    "<5d>": "]",
    "<40>": "@",
    "<23>": "#",
    "<25>": "%",
    "<5e>": "^",
    "<26>": "&",
    "<5f>": "_",
    "<5c>": "\",
    "<24>": "$",
}

def str_replace(source):
    target = source
    for k, v in str_dict.items():
        if k in source:
            target = source.replace(k, v)
            str_replace(target)
    return target

我想将 s1 中的这些特殊 str 替换为它们的 dict' 值。

str_replace(source) 是我的函数

但是如果特殊的strs1中不止一个,它只是替换第一个

我只是对你的 str_replace() 做了一点改动,看起来效果不错:

s1 = "1$<2d>46<2e>5"
s2 = "Hi<2c> have a nice day <26> take care <40>Someone <40>Someone"

str_dict = {
    "<2c>": ",",
    "<2e>": ".",
    "<2f>": "/",
    "<2d>": "-",
    "<2b>": "+",
    "<3d>": "=",
    "<3f>": "?",
    "<2a>": "*",
    "<5d>": "]",
    "<40>": "@",
    "<23>": "#",
    "<25>": "%",
    "<5e>": "^",
    "<26>": "&",
    "<5f>": "_",
    "<5c>": "\",
    "<24>": "$",
}

def str_replace(source):
    target = source
    for k, v in str_dict.items():
        if k in target:
            target = target.replace(k, v)
    return target

print(str_replace(s1))
print(str_replace(s2))

# ----output-----
1$-46.5
Hi, have a nice day & take care @Someone @Someone

如果没有设置countstr.replace(old, new[, count])可以替换所有匹配的模式。