pjdavis
pjdavis

Reputation: 345

Python string replace method - replacing multiple instances of a word

def translate(sent):
    trans={"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"år"}
    word_list = sent.split(' ')
    for word in word_list:
    for i,j in trans.items():
        if j == word:
            return sent.replace(word, i)

>>>translate('xmas greeting: god jul och gott nytt år') 
'xmas greeting: merry jul och gott nytt år'

I'm trying to write a function which will take in a string replace words which match values in a dictionary with their corresponding keys. It is really frustrating as I can only replace one word (using the replace method). How can I replace more than one word?

Upvotes: 1

Views: 233

Answers (2)

Fuji Komalan
Fuji Komalan

Reputation: 2047

mystring = 'this is my table pen is on the table '

trans_table = {'this':'that' , 'is':'was' , 'table':'chair'}

final_string = ''

words = mystring.split()

for word in words:
  if word in trans_table:
    new_word = trans_table[word]
    final_string = final_string + new_word + ' '
  else:    
    final_string = final_string + word + ' '

print('Original String :', mystring)
print('Final String :' , final_string)

Upvotes: 0

akuiper
akuiper

Reputation: 214957

You need to assign the replaced result back to sent, after the for loop exhausted, then return the sent:

def translate(sent):
    trans={"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"år"}
    word_list = sent.split(' ')
    for word in word_list:
        for i,j in trans.items():
            if j == word:
                sent = sent.replace(word, i)
    return sent

translate('xmas greeting: god jul och gott nytt år') 
# 'xmas greeting: merry christmas and happy new year'

Upvotes: 3

Related Questions