ma_tthews
ma_tthews

Reputation: 15

How to replace words in a string (python)

I need to replace "cry" with "fly" and "want to" with "will" in the string below.

message ="I want to cry"

I tried this:

print(message.replace("cry", "fly")("want to","will")) 

it doesnt work

Upvotes: 0

Views: 55

Answers (2)

Bhavya Parikh
Bhavya Parikh

Reputation: 3400

You can create a dictionary of data that you want to replace

message ="I want to cry"

change_word={"cry":"fly","want to":"will"}

for key,value in change_word.items():
    message=message.replace(key,value)
print(message)

Upvotes: 0

Barmar
Barmar

Reputation: 782653

You need a separate call to .replace() for each replacement.

print(message.replace("cry", "fly").replace("want to","will")) 

Upvotes: 3

Related Questions