-1

I have the following sentence "the man went to the shop" and I want to replace any word that has "th" or "sh" with "dogs. The results should look something like this:

dogse man went to dogse dogsop

This is what my code looks like so far:

sentence = "the man went to the shop"

to_be_replaced = ["th", "sh"]
replaced_with = "dogs"

for terms in to_be_replaced:
    if terms in sentence:
        new_sentence = sentence.replace(terms,replaced_with)
        print new_sentence

Currently, this prints:

dogse man went to dogse shop
the man went to the dogsop

I want it to print this only:

dogse man went to dogse dogsop

I would I go about doing this?

semiflex
  • 1,176
  • 3
  • 25
  • 44
  • Not the best implementation, but it will work if you re-bind to `sentence`; change `new_sentence` to `sentence` – Chris_Rands Dec 16 '16 at 13:52

3 Answers3

4

This should work:

s.replace("th", "dogs").replace("sh", "dogs")
Carles Mitjans
  • 4,786
  • 3
  • 19
  • 38
1

You just have to work on the same string from the start and keep working on it. You don't need your new_sentence (except if you want to keep the first).

This code should work :

sentence = "the man went to the shop"

to_be_replaced = ["th", "sh"]
replaced_with = "dogs"

for terms in to_be_replaced:
    if terms in sentence:
        sentence = sentence.replace(terms,replaced_with)
print sentence

It should print :

dogse man went to dogse dogsop
iFlo
  • 1,442
  • 10
  • 19
1
import re

text = "the man went to the shop"
repalceed = re.sub(r'sh|th', 'dogs', text)
print(repalceed)

out:

dogse man went to dogse dogsop
宏杰李
  • 11,820
  • 2
  • 28
  • 35