Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string replacement [duplicate]

Tags:

python

string

I'm trying to replace the occurrence of a word with another:

word_list = { "ugh" : "disappointed"}

tmp = ['laughing ugh']

for index, data in enumerate(tmp):
    for key, value in word_list.iteritems():
        if key in data:
            tmp[index]=data.replace(key, word_list[key])

print tmp

Whereas this works... the occurrence of ugh in laughing is also being replaced in the output: ladisappointeding disappointed.

How does one avoid this so that the output is laughing disappointed?

like image 760
user47467 Avatar asked Feb 24 '16 10:02

user47467


People also ask

How do you replace all occurrences of a string in Python?

The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.


1 Answers

In that case, you may want to consider to replace word by word.

Example:

word_list = { "ugh" : "disappointed"}
tmp = ['laughing ugh']

for t in tmp:
    words = t.split()
    for i in range(len(words)):
        if words[i] in word_list.keys():
            words[i] = word_list[words[i]]
    newline = " ".join(words)
    print(newline)

Output:

laughing disappointed

Step-by-Step Explanations:

  1. Get every sentence in the tmp list:

    for t in tmp:
    
  2. split the sentence into words:

    words = t.split()
    
  3. check whether any word in words are in the word_list keys. If it does, replace it with its value:

    for i in range(len(words)):
        if words[i] in word_list.keys():
            words[i] = word_list[words[i]]
    
  4. rejoin the replaced words and print the result out:

    newline = " ".join(words)
    print(newline)
    
like image 189
Ian Avatar answered Oct 11 '22 23:10

Ian