In this HowTo i’ll explain how the Python string replace method is used to make changes to a string.
What is the Python string replace method?
There are times when you might want to make changes to an existing string in Python and you can use the Python string replace method to change parts of an existing string. Before anybody shoots me and roars at the top of their voice “But Python strings are immutable - they can’t be changed!” I want to just “Yes, you are right but it won’t affect us for this HowTo”. I’ll explain more later on. So the basic way to use the Python string replace method is to call it on an existing string or variable:
'Learn to code'.replace('code', 'program') # Returns the string 'Learn to program' message = 'Nice to meet you, nice.' message.replace('Nice', 'Great') # Returns the string 'Great to meet you'
You can also limit the number of replacements that are performed with the replace() method:
message = 'Nice to meet you. Nice.' message.replace('Nice', 'Great', 1) # Returns the string 'Great to meet you. Nice.'
Of course, the Python string replace method only returns the newly modified string. In order to make the changes permanently stick to a variable you need to assign the returned string to the same or new variable.
string = 'The quick brown fox' string = string.replace('fox', 'cow') # Equals 'The quick brown cow'
Note: Whilst this looks like you are modifying the string (remember they can’t be changed!) you aren’t. The value stored in string is just replaced with the value returned from the replace() method. The replace() method is case sensitive so you’ll need to make sure the strings you are using to replace match what is in the text. An alternative to this would be to use a more complicated regular expression.
string = 'Please, please, PLEASE!' string.replace('please', 'thank you') # Returns 'Please, thank you, PLEASE!'
In the above example only the middle ‘please’ is replaced as it’s the only one that matches.
The Python string replace method is fairly self explanatory. You call it on an existing string (either a literal or a variable) and then pass in what you want to be replaced and with what. The replace() method is case senstitive so it won’t match everything if there is any capitlisation.