0

I am working with Python 3 and I want to replace the emoticons included in a dictionary.

For example

text = "Hi, I'm coming home :)"

#Create dictionary
dict_lookup = {':(' : 'sad',
               ':)' : 'happy'}

The desired output is:

Hi, I'm coming home happy

What is the most efficient way to achieve this result in Python 3?

Alex
  • 1,447
  • 7
  • 23
  • 48

2 Answers2

4

This should do the trick:

for emote, replacement in dict_lookup.items():
      text = text.replace(emote, replacement)
Błażej Michalik
  • 4,474
  • 40
  • 55
  • Does it make sense to use Regular Expression (re) in this case? – Alex Aug 08 '17 at 12:22
  • @Alex for such use cases `replace()` is always enough. Regular expressions come into play when you can't find the substring that you want to replace with a simple comparison. – Błażej Michalik Aug 08 '17 at 12:26
1

Take a look at str.replace

It allows you to do text.replace(dict_key, dict_value)

MrPromethee
  • 721
  • 9
  • 18