Python's String.replace() Method
The string.replace()
method is a convenient way of changing an recurring expression inside a string to another expression - in other words, to replace all occurrences of a string within another string. The notation is:
modified_string = my_string.replace('text_I_want_to_change', 'new_text')
Note that this is not an inplace operator - we need to assign the result to some variable to persist the change. Our original string is unchanged:
my_string = 'Hello, my name is Felipe'
modified_string = my_string.replace('Felipe','John')
print(my_string)
print(modified_string)
Hello, my name is Felipe
Hello, my name is John
Replace First N Occurrences in String
The string.replace()
method has an optional parameter that defines how many instances of the text we want to replace (first n get replaced, none after):
my_string = 'Hello, my name is Felipe'
modified_string = my_string.replace('e', '3', 2)
print(modified_string)
H3llo, my nam3 is Felipe
Note: Finally, if the first parameter of string.replace() is not found, the string is unchanged. No error code is returned.
my_string = 'Hello, my name is Felipe'
modified_string = my_string.replace('x', '3')
print(modified_string)
Hello, my name is Felipe
Advice: If you're looking for an expanded topic on replacing occurrences of strings within strings - you can also employ Regular Expressions, customize pattern-matching rules, etc. In that case, read our "Replace Occurrences of a Substring in String with Python"!