用Python替换部分字符串?

时间:2012-04-06 00:14:29

标签: python

  

可能重复:
  python regular expression replacing part of a matched string

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

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

3 个答案:

答案 0 :(得分:67)

>>> stuff = "Big and small"
>>> stuff.replace(" and ","/")
'Big/small'

答案 1 :(得分:20)

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

>>> stuff = "Big and small"
>>> stuff.replace( " and ", "/" )
'Big/small'

答案 2 :(得分:4)

您也可以轻松使用.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'
相关问题