67

I used regular expressions to get a string from a web page and part of the string may contain something I would like to replace with something else. How would it be possible to do this? My code is this, for example:

stuff = "Big and small"
if stuff.find(" and ") == -1:
    # make stuff "Big/small"
else:
    stuff = stuff
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Markum
  • 3,919
  • 8
  • 26
  • 30

3 Answers3

100
>>> stuff = "Big and small"
>>> stuff.replace(" and ","/")
'Big/small'
jamylak
  • 128,818
  • 30
  • 231
  • 230
21

Use the replace() method on string:

>>> stuff = "Big and small"
>>> stuff.replace( " and ", "/" )
'Big/small'
Russell Borogove
  • 18,516
  • 4
  • 43
  • 50
9

You can easily use .replace() as also previously described. But it is also important to keep in mind that strings are immutable. Hence if you do not assign the change you are making to a variable, then you will not see any change. Let me explain by;

    >>stuff = "bin and small"
    >>stuff.replace('and', ',')
    >>print(stuff)
    "big and small" #no change

To observe the change you want to apply, you can assign same or another variable;

    >>stuff = "big and small"
    >>stuff = stuff.replace("and", ",")   
    >>print(stuff)
    'big, small'
Dharman
  • 30,962
  • 25
  • 85
  • 135
Kubra Altun
  • 365
  • 3
  • 12