2

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"
1
  • Have you looked at the replace method of the str class? E.g., 'hello'.replace('l','abc') producing 'heabcabco'. Commented Jun 24, 2020 at 1:25

1 Answer 1

3

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']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.