简体   繁体   中英

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

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM