65

我使用正则表达式从网页获取字符串,部分字符串可能包含我想用其他内容替换的内容。怎么可能做到这一点?我的代码是这样的,例如:

stuff = "Big and small"
if stuff.find(" and ") == -1:
    # make stuff "Big/small"
else:
    stuff = stuff
4

3 回答 3

96
>>> stuff = "Big and small"
>>> stuff.replace(" and ","/")
'Big/small'
于 2012-04-06T00:16:00.123 回答
20

replace()在字符串上使用方法:

>>> stuff = "Big and small"
>>> stuff.replace( " and ", "/" )
'Big/small'
于 2012-04-06T00:16:10.537 回答
9

.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'
于 2020-08-24T12:56:57.077 回答