Replace part of a string in Python?

PythonString

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

Use the replace() method on string:

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

Solution 3 - Python

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'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarkumView Question on Stackoverflow
Solution 1 - PythonjamylakView Answer on Stackoverflow
Solution 2 - PythonRussell BorogoveView Answer on Stackoverflow
Solution 3 - PythonKubra TasView Answer on Stackoverflow