-1

I have a question I need to resolve, for example:

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

I want to replace these special str in s1 into their dict's value.

str_replace(source) is my function

but if the special str is more than one in s1, it just replaces the first place

blurfus
  • 13,485
  • 8
  • 55
  • 61
iamjing66
  • 61
  • 6
  • or any faster way to solve it – iamjing66 Sep 17 '21 at 05:30
  • Don't bother with the `if k in source:` check. If its not there it just wont replace it. The check is not free, its required to iterate the string to look for the substring. Also did you mean `target = target.replace(k, v)`? and why the recursive call? You already have the loop and you throw away the return value. – Paul Rooney Sep 17 '21 at 05:39
  • @Paul Rooney yes ,I just use `target = target.replace(k, v)` and it works,but is there faster way? – iamjing66 Sep 17 '21 at 05:43
  • This one is useful [How to replace multiple substrings of a string?](https://stackoverflow.com/a/69195618/16239086),thank you all,it solved – iamjing66 Sep 17 '21 at 05:54
  • That link might be an overkill, how about `import re` and then `target = re.sub('<\w\w>', lambda m:str_dict.get(m.group(0), m.group(0)), "1$<2d>46<2e>5")` – LemonPy Sep 17 '21 at 07:49

1 Answers1

0

I just change a little from your str_replace() and it seems work well:

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

The str.replace(old, new[, count]) can replace all the matched patterns if you didn't set the count.

Tim yuan
  • 26
  • 3