简体   繁体   中英

Python3 - replace string require if statement?

I just want to replace 'dog' with anything!

Think I need an if statement but can't get one that makes sense:

wordlist = ['cat','dog','rabbit','test',]

letterlist = []
for aword in wordlist:
    aword.replace('dog', 'OMG IT WORKED? OR NOT')
    print (aword)
    letterlist.append(aword)

print(letterlist)

str.replace() returns a new string ; you want to rebind aword to it:

aword = aword.replace('dog', 'OMG IT WORKED? OR NOT')

str is an immutable type; you can only produce a new value with changes, not change the value itself.

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