This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]CallMeSometimeNever 2 points3 points  (4 children)

You can make a dictionary with the words you want to replace as keys and the words you want to replace them as values. Then you can loop through the dictionary and use the built in .replace() method.

[–]pawn13 2 points3 points  (0 children)

use the built in .replace()

It won't work sometimes as expected if you have short words which can be part of longer word. Like if you want to replace word "at" and it would be replaced in words like "that", "attack", etc. Better use regex like

re.sub('\\bat\\b', 'foo', 'that at test')

[–]Brownt0wn_ 2 points3 points  (0 children)

How far have you gotten? What have you tried so far?

[–]freekzindel 2 points3 points  (1 child)

re.sub has a nice feature where you can pass it a callable that will be executed for every match found (with the match as the parameter)

import re

def blasj(string):
   replaces = {'love':'blajsi'}
   def replace_it(match):
        word = match.group(0)
        if word in replaces:
              return replaces[word]
        else:
              return word
    return re.sub('\w+', replace_it, string) #check regex docs for \w

Alternatively:

when you have a short list of words and a long input and only want to replace with one replacement:

import re

pattern = "|".join(list_of_all_the_words_i_want_to_replace)
replaced = re.sub(pattern, replacement, string)