简体   繁体   English

Python3-替换字符串是否需要if语句?

[英]Python3 - replace string require if statement?

I just want to replace 'dog' with anything! 我只想用任何东西代替'dog'

Think I need an if statement but can't get one that makes sense: 想想我需要一个if语句,但不能得到一个有意义的语句:

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 ; str.replace() 返回一个新字符串 you want to rebind aword to it: 您想重新绑定aword

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

str is an immutable type; str是不可变的类型; you can only produce a new value with changes, not change the value itself. 您只能通过更改产生一个新值,而不能更改值本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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