Python replace function [replace once]

前端 未结 6 1544
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 12:40

I need help with a program I\'m making in Python.

Assume I wanted to replace every instance of the word \"steak\" to \"ghost\" (just go wit

6条回答
  •  眼角桃花
    2020-12-01 13:11

    How about something like this? Store the original in a split list, then have a translation dict. Keeps your core code short, then just adjust the dict when you need to adjust the translation. Plus, easy to port to a function:

     def translate_line(s, translation_dict):
        line = []
        for i in s.split():
           # To take account for punctuation, strip all non-alnum from the
           # word before looking up the translation.
           i = ''.join(ch for ch in i if ch.isalnum()]
           line.append(translation_dict.get(i, i))
        return ' '.join(line)
    
    
     >>> translate_line("The scary ghost ordered an expensive steak", {'steak': 'ghost', 'ghost': 'steak'})
     'The scary steak ordered an expensive ghost'
    

提交回复
热议问题