A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/replace-in-python-to-replace-a-substring/ below:

replace() in Python to replace a substring

replace() in Python to replace a substring

Last Updated : 31 Jan, 2025

replace() method in Python allows us to replace a specific part of a string with a new value. It returns a new string with the change without modifying the original one. We can also specify how many times the replacement should occur.

For Example:

Python
s = "hlo AB world"
# Replace "AB" with "C" in `s`
res = s.replace("AB", "C")
print(res)
Syntax:

str.replace(pattern,replaceWith,maxCount)

Parameters:

It means replacing multiple spaces between words with a single space or completely removing them to clean up the text.

Python
s = "Geeks  For   Geeks"

# Replacing all spaces with an empty string
res = s.replace(" ", "")
print(res)
Converting a date format

We can use replace() to convert a date format from one style to another.

Python
# Backend date format
date = "2025-01-21"

# Converting the date format to DD/MM/YYYY
res = date.replace("-", "/").split("/")
res = f"{res[2]}/{res[1]}/{res[0]}"
print(res)


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4