exenlediatán
exenlediatán

Reputation: 109

How do I replace specific word from string with values of a list in Python?

I have a string that contains two times the word "change". I'm trying to replace that word with the values that I have on a list generated by a query of sql using python.

  1. str = "I do not want to change my pants because they change my humor"
  2. list= ["number one","number two","number four"]
  3. Output should be equal to: "I do not want to number one my pants because they number one my humor" "I do not want to number two my pants because they number two my humor" "I do not want to number four my pants because they number four my humor"

Upvotes: 2

Views: 382

Answers (1)

Red
Red

Reputation: 27547

You can use the replace() method:

st = "I do not want to change my pants because they change my humor"
lst= ["number one","number two","number four"]
for s in lst:
    print(st.replace('change',s))

Output:

I do not want to number one my pants because they number one my humor
I do not want to number two my pants because they number two my humor
I do not want to number four my pants because they number four my humor

If you want to store the strings in a list:

st = "I do not want to change my pants because they change my humor"
lst= ["number one","number two","number four"]
print([st.replace('change',s) for s in lst])

Output:

['I do not want to number one my pants because they number one my humor',
 'I do not want to number two my pants because they number two my humor',
 'I do not want to number four my pants because they number four my humor']

Upvotes: 3

Related Questions