Hypothetical Ninja
Hypothetical Ninja

Reputation: 4077

Replace Multiple Words in a string

i have the foll txt:

txt = "there was a nr opp rd bldg"

and i need to replace them with their correct spellings.. so i made a small replacement dictionary

rep = {"rd": "road", "nr": "near","opp":"opposite","bldg":"building"} 

and used the following code:

def replace_all(text, rep):  
    for i, j in rep.iteritems():  
        text = text.replace(i, j)  
    return text 

replace_all(txt,rep)
print txt  

but the output dint change.. What could be the reason?

Upvotes: 0

Views: 1491

Answers (1)

barak manos
barak manos

Reputation: 30146

Function replace_all changes a local variable text and then returns it.

Your mistake is not assigning the returned value into the global variable txt.

Use txt = replace_all(txt,rep), and it should solve your problem.

Upvotes: 5

Related Questions