Python's String.replace() Method

# 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):

## Get free courses, guided projects, and more

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"!

Last Updated: November 12th, 2022
Project

### Building Your First Convolutional Neural Network With Keras

# python# artificial intelligence# machine learning# tensorflow

Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...

David Landup
Details
Course

### Data Visualization in Python with Matplotlib and Pandas

# python# pandas# matplotlib

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

David Landup
Details