我使用正则表达式从网页获取字符串,部分字符串可能包含我想用其他内容替换的内容。怎么可能做到这一点?我的代码是这样的,例如:
stuff = "Big and small"
if stuff.find(" and ") == -1:
# make stuff "Big/small"
else:
stuff = stuff
>>> stuff = "Big and small"
>>> stuff.replace(" and ","/")
'Big/small'
replace()
在字符串上使用方法:
>>> stuff = "Big and small"
>>> stuff.replace( " and ", "/" )
'Big/small'
.replace()
您也可以像前面描述的那样轻松使用。但同样重要的是要记住字符串是不可变的。因此,如果您不将所做的更改分配给变量,那么您将看不到任何更改。让我解释一下;
>>stuff = "bin and small"
>>stuff.replace('and', ',')
>>print(stuff)
"big and small" #no change
要观察您要应用的更改,您可以分配相同或另一个变量;
>>stuff = "big and small"
>>stuff = stuff.replace("and", ",")
>>print(stuff)
'big, small'