Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
replace() in Python to replace a substring
Next article icon

Python – Replace all occurrences of a substring in a string

Last Updated : 08 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Replacing all occurrences of a substring in a string means identifying every instance of a specific sequence of characters within a string and substituting it with another sequence of characters.

Using replace()

replace () method is the most straightforward and efficient way to replace all occurrences of a substring in Python.

Python
a = "python java python html python"  res = a.replace("python", "c++") print(res) 

Output
c++ java c++ html c++ 

Explanation:

  • replace() method replaces all occurrences of the specified substring with the new string.
  • This method is highly efficient for string replacement tasks and works seamlessly for all string sizes.

Let’s explore different methods to replace all occurrences of a substring in a string.

Table of Content

  • Using regular expressions
  • Using string splitting and joining
  • Using a manual loop

Using regular expressions

For complex patterns, regular expressions allow us to replace substrings based on a pattern.

Python
import re  s = "python java python html python" res = re.sub("python", "c++", s) print(res) 

Output
c++ java c++ html c++ 

Explanation:

  • Regular expressions search for a specific pattern and replace all its matches with the replacement string.
  • They are versatile and powerful for handling dynamic or complex patterns.

Using string splitting and joining

This approach involves splitting the string at the substring and rejoining the parts with the desired replacement.

Python
s = "python java python html python"  res = "c++".join(s.split("python")) print(res) 

Output
c++ java c++ html c++ 

Explanation:

  • split() method breaks the string into parts using the target substring.
  • join() method combines these parts with the replacement string.
  • While functional, this method is less efficient than replace for simple replacements.

Using a manual loop

A manual loop can iterate through the string and build a new one by replacing the target substring.

Python
s = "python java python html python" target = "python" replacement = "c++" res = ""  i = 0 while i < len(s):     if s[i:i+len(target)] == target:         res += replacement         i += len(target)     else:         res += s[i]         i += 1  print(res) 

Output
c++ java c++ html c++ 

Explanation:

  • This method manually searches for the target substring and replaces it with the desired string.


Next Article
replace() in Python to replace a substring
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • replace() in Python to replace a substring
    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: [GFGTABS] Python s = "hlo AB world" # Repl
    2 min read
  • Replacing Characters in a String Using Dictionary in Python
    In Python, we can replace characters in a string dynamically based on a dictionary. Each key in the dictionary represents the character to be replaced, and its value specifies the replacement. For example, given the string "hello world" and a dictionary {'h': 'H', 'o': 'O'}, the output would be "Hel
    2 min read
  • Python - Replacing Nth occurrence of multiple characters in a String with the given character
    Replacing the Nth occurrence of multiple characters in a string with a given character involves identifying and counting specific character occurrences. Using a Loop and find()Using a loop and find() method allows us to search for the first occurrence of a substring within each list element. This ap
    2 min read
  • Python - Check if substring present in string
    The task is to check if a specific substring is present within a larger string. Python offers several methods to perform this check, from simple string methods to more advanced techniques. In this article, we'll explore these different methods to efficiently perform this check. Using in operatorThis
    2 min read
  • How to Substring a String in Python
    A String is a collection of characters arranged in a particular order. A portion of a string is known as a substring. For instance, suppose we have the string "GeeksForGeeks". In that case, some of its substrings are "Geeks", "For", "eeks", and so on. This article will discuss how to substring a str
    4 min read
  • Find all the patterns of “1(0+)1” in a given string using Python Regex
    A string contains patterns of the form 1(0+)1 where (0+) represents any non-empty consecutive sequence of 0’s. Count all such patterns. The patterns are allowed to overlap. Note : It contains digits and lowercase characters only. The string is not necessarily a binary. 100201 is not a valid pattern.
    2 min read
  • Python - Remove empty strings from list of strings
    When working with lists of strings in Python, you may encounter empty strings (" ") that need to be removed. We'll explore various methods to Remove empty strings from a list. Using List ComprehensionList comprehension is the most concise and efficient method to filter out empty strings. This method
    2 min read
  • Print all subsequences of a string in Python
    Given a string s of size n (1 ≤ n ≤ 20), the task is to print all subsequences of string. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. Examples: Input: s = "abc"Output: ["", "a", "b", "c",
    3 min read
  • Python | Remove Redundant Substrings from Strings List
    Given list of Strings, task is to remove all the strings, which are substrings of other Strings. Input : test_list = ["Gfg", "Gfg is best", "Geeks", "for", "Gfg is for Geeks"] Output : ['Gfg is best', 'Gfg is for Geeks'] Explanation : "Gfg", "for" and "Geeks" are present as substrings in other strin
    5 min read
  • Check if String Contains Substring in Python
    This article will cover how to check if a Python string contains another string or a substring in Python. Given two strings, check whether a substring is in the given string. Input: Substring = "geeks" String="geeks for geeks"Output: yesInput: Substring = "geek" String="geeks for geeks"Output: yesEx
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences