How to replace a substring inside a string in Python

How to replace a substring inside a string in Python

In this Python String Replace tutorial, we will talk about how to replace a substring inside a string in Python, using the replace() method. In Python, strings are represented as immutable str objects. The str class comes with many methods that allow you to manipulate strings.

In this article, we will talk about how to replace a substring inside a string in Python, using the replace() method.

.replace() Method

In Python, strings are represented as immutable str objects. The str class comes with many methods that allow you to manipulate strings.

The .replace() method takes the following syntax:

str.replace(old, new[, maxreplace])
  • str - The string you are working with.
  • old – The substring you want to replace.
  • new – The substring that replaces the old substring.
  • maxreplace – Optional argument. The number of matches of the old substring you want to replace. The matches are counted from the beginning of the string.

The method returns a copy of the string srt with some or all matches of substring old replaced by new. If maxreplace is not given, all occurrences are be replaced.

In the example below we're replacing the substring far in string s with miles:

s = 'A long time ago in a galaxy far, far away.'
s.replace('far', 'miles')

The result is a new string:

'A long time ago in a galaxy miles, miles away.'

String literals are usually enclosed by single quotes, although double quotes can be used too.

When the optional maxreplace argument is given, it will limit the number of replaced matches. In the following example we're replacing only the first occurrence:

s = 'My ally is the Force, and a powerful ally it is.'
s.replace('ally', 'friend', 1)

The result string will look like this:

'My friend is the Force, and a powerful ally it is.'

To delete a substring, use an empty string '' as a replacement. For example to remove space from the following string you would use:

s = 'That’s no moon. It’s a space station.'
s.replace('space ', '')

The new string will look like the following:

`That’s no moon. It’s a station.'

Replace Substring in List of Strings

To replace a substring in a list of strings, use the list comprehension construct as show below:

s.replace('old', 'new') for s in list

Let's take a look at the following example:

names = ['Anna Grace', 'Betty Grace', 'Emma Grace']
new_names = [s.replace('Grace', 'Lee') for s in names]
print(new_names)

The code above creates a copy of the list with all occurrences of substring Grace replaced by Lee:

['Anna Lee', 'Betty Lee', 'Emma Lee']

Conclusion

Replacing a substring in a string is one of the most basic operations when writing code in Python. After reading this tutorial, you should have a good understanding of how to use the replace() method.

If you have any questions or feedback, feel free to leave a comment.

Python

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

How To Compare Tesla and Ford Company By Using Magic Methods in Python

Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc.. You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like __init__, __call__, __str__ etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).

Python Programming: A Beginner’s Guide

Python is an interpreted, high-level, powerful general-purpose programming language. You may ask, Python’s a snake right? and Why is this programming language named after it?

Hire Python Developers

Are you looking for experienced, reliable, and qualified Python developers? If yes, you have reached the right place. At **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")**, our full-stack Python development services...

Python any: How to Check If Element is Iterable or Not

Python any() function returns True if any element of an iterable is True otherwise any() function returns False. The syntax is any().