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

2024-05-29 02:57:36 发布

您现在位置: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中不止一个,那么它只会替换第一个位置


Tags: insourcetargetforreturnifdefitems
1条回答
网友
1楼 · 发布于 2024-05-29 02:57:36

我只是对你的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

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

相关问题 更多 >

    热门问题