Python replace function [replace once]
I’d probably use a regex here: >>> import re >>> s = “The scary ghost ordered an expensive steak” >>> sub_dict = {‘ghost’:’steak’,’steak’:’ghost’} >>> regex = ‘|’.join(sub_dict) >>> re.sub(regex, lambda m: sub_dict[m.group()], s) ‘The scary steak ordered an expensive ghost’ Or, as a function which you can copy/paste: import re def word_replace(replace_dict,s): regex = ‘|’.join(replace_dict) … Read more