Replace String in Python

Often you’ll have a string (str object), where you will want to modify the contents by replacing one piece of text with another. In Python, everything is an object – including strings. This includes the str object. Luckily, Python’s string module comes with a replace() method. The replace() method is part of the string module, and can be called either from a str object or from the string module alone.

Python’s string.replace() Prototype

The prototype of the string.replace() method is as follows:

string.replace(s, old, new[, maxreplace])
Function parameters
    • s: The string to search and replace from.
    • old: The old sub-string you wish to replace.
  • new: The new sub-string you wish to put in-place of the old one.
  • maxreplace: The maximum number of times you wish to replace the sub-string.

Examples

Sring Module

our_str = 'Hello World'

import string
 
new_str = string.replace(our_str, 'World', 'Justice')
print(new_str)
 
new_str = string.replace(our_str, 'Hello', 'Hello,')
print(new_str)
 
our_str = 'Hello you, you and you!'
new_str = string.replace(our_str, 'you', 'me', 1)
print(new_str)
new_str = string.replace(our_str, 'you', 'me', 2)
print(new_str)
new_str = string.replace(our_str, 'you', 'me', 3)
print(new_str)

This gives us the following output:

Hello Justice
Hello, World
Hello me, you and you!
Hello me, me and you!
Hello me, me and me!

And using the string.replace() method from the str object:

our_str = 'Hello World'
 
new_str = our_str.replace('World', 'Justice')
print(new_str)
 
new_str = our_str.replace('Hello', 'Hello,')
print(new_str)
 
our_str = 'Hello you, you and you!'
new_str = our_str.replace('you', 'me', 1)
print(new_str)
new_str = our_str.replace('you', 'me', 2)
print(new_str)
new_str = our_str.replace('you', 'me', 3)
print(new_str)

Which gives us:

Hello Jackson
Hello, World
Hello me, you and you!
Hello me, me and you!
Hello me, me and me!

 

Subscribe

Related articles

There is brand-new Xiaomi Wireless AR Smart Glasses

Xiaomi, the Chinese multinational electronics company, has recently launched...

The OnePlus 11R has been revealed to use a Snapdragon 8+ Gen 1 processor

OnePlus is having a big event on February 7, where...

Zoom Lays Off 1,300 Employees: A Look at the Impact and Reactions

Zoom, the popular video conferencing platform, has recently announced...

The Future of Bitcoin and Cryptocurrency Outlook in 2023

Bitcoin and cryptocurrency have come a long way since...
Amarendra Singh
Amarendra Singh
Stock Trader, SEO, Music Producer

Leave a reply

Please enter your comment!
Please enter your name here