-3

Hey guys how can I replace multiple numbers in a string for their values specified in a dict in one go? ex:

dic_lanches = {10:'Misto-Quente',11:'X-Burger',
               12:'X-Salada',
               13:'X-Egg',
               14:'X-Bacon',
               15:'X-Calabresa',
               16:'X-Frango',
               17:'X-Coração',
               18:'X-Casa'}

my_string = 11 12 13

after replace:

I want X-Burguer X-Salada X-Egg

But what I am getting is:

X-Burguer 12 13

11 X-Salada 13

11 12 X-Egg

now tried:

result = re.sub(r'\d', lambda x: dic_lanches[int(x.group())], myString)

but I'm getting KeyError 1

  • 2
    Possible duplicate of [Python replace multiple strings](https://stackoverflow.com/questions/6116978/python-replace-multiple-strings) – Dylan Lawrence Dec 08 '17 at 16:52

1 Answers1

1

Using re:

import re
myString = "I want 11 12 13"
result = re.sub(r'\d', lambda x: dic_lanches[int(x.group())], myString)

What we are doing here is we use regex to match all numbers in the string, then we replace those numbers with the string in the dict that has the corresponding key.

stelioslogothetis
  • 9,371
  • 3
  • 28
  • 53