Python string replace method - replacing multiple instances of a word

前端 未结 2 1858
谎友^
谎友^ 2021-01-23 22:12
def translate(sent):
    trans={\"merry\":\"god\", \"christmas\":\"jul\", \"and\":\"och\", \"happy\":\"gott\", \"new\":\"nytt\", \"year\":\"år\"}
    word_list = sent.sp         


        
2条回答
  •  青春惊慌失措
    2021-01-23 23:07

    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)
    

提交回复
热议问题