Home > Mobile >  Cant replace all the word with replacement in python based on the match in dictionary list
Cant replace all the word with replacement in python based on the match in dictionary list

Time:09-05

I tried to replace the word in a string with the value in a dictionary if its matched.

My code:

test_dict = {"valuation": "none", "other": "test"}
for word, replacement in test_dict.items():
    if word in "other valuation $$$":
        strValue = "other valuation $$$".replace(word, replacement)

My current output:

'test valuation $$$'

My expected output:

'test none $$$'

is there a way to do it in single line? If not any types is fine.

CodePudding user response:

This is because you change the strValue value back to the initial string.

test_dict = {"valuation": "none", "other": "test"}
strValue = "other valuation $$$"
for word, replacement in test_dict.items():
    strValue = strValue.replace(word, replacement)
print(strValue)

You can do the same in one line also but it also makes list with None values.

test_dict = {"valuation": "none", "other": "test"}
strValue = ["other valuation $$$"]


[strValue.append(strValue[-1].replace(word,replacement)) for word,replacement in test_dict.items()]

print(strValue[-1])

output

test none $$$
  • Related