TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Replace All or Some Occurrences of Chars/Sub Strings
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python ExamplesPython Tutorials

Replace All or Some Occurrences of Chars/Sub Strings

Last updated: Nov 05, 2023 12:08 am
By Meenakshi Agarwal
Share
5 Min Read
Replace all or specified no. of occurrences of chars sub strings in Python
Replace all or specified no. of occurrences of chars sub strings in Python
SHARE

This Python programming example explains how to replace occurrences (single or all) of a character in a string. It tells the complete logic in detail.

Contents
Replace all occurrences of a char/string in a stringReplace num occurrences of a char/string in a stringHow to replace multiple chars/substring in a string?

In this short tutorial, we are going to use Python’s str.replace() function to do our task of replacing a char in the target string. It is a very common requirement for programmers when they want to modify the original string by substituting with some value.

Must check out this post – Python Replace String with Examples

Python String Replace Function

This method has the following syntax:

# Python's String Replace Function

python_string.replace(old_str, new_str, count)

Parameters:

 old_str => Old string to be replaced
 new_str => New string used for substitution
 count => Replacement counter

Returns:

 Returns a copy of the old string with the new after replacment.

The above function creates a new string and returns the same. It contains a copy of the original value replaced with the new one.

You should note the following points while using the string.replace() method:

  • If the count parameter is not specified, then all occurrences of the old string will get replaced with the new one.
  • It there is some value in the count parameter, then the old string will get replaced specified no. of time by the new one.

Let’s now do some hands-on with examples.

Replace all occurrences of a char/string in a string

Assume we have the following original string:

original_str = "Python Programming language is easy to learn and easy to code."

Your task is to replace all occurrences of string “easy” with the following:

replace_str = "simple"

Here is the sample Python code to achieve this:

"""
Example:
 Replace all occurrences of the specifed string in the original string
"""
final_str = original_str.replace("easy" , replace_str) 
print(final_str)

The output is as follows:

Python Programming language is simple to learn and simple to code.

Let’s check out one more example that replaces a character with another one in the original string.

original_char = '.'
replace_char = '!'

Below code does the needful.

"""
Example:
 Replace all occurrences of a given char in the original string
"""
final_str = original_str.replace(original_char ,  replace_char) 
print(final_str)

The output is as follows:

Python Programming language is easy to learn and easy to code!

Replace num occurrences of a char/string in a string

Let’s do our test with the following original string:

original_str = "Python Programming language, Python Programmer, Python Unit Testing."

Your task is to replace the first two occurrences of string “Python” with the following:

replace_str = "CSharp"

Here is the sample Python code to achieve this:

"""
Example:
 Replace first two occurrences of the specifed string in the original string
"""
final_str = original_str.replace("Python" , replace_str, 2) 
print(final_str)

The output is as follows:

CSharp Programming language, CSharp Programmer, Python Unit Testing.

Since we have supplied 2 as the count argument value, so it would only replace the first two occurrences of “Python” string.

How to replace multiple chars/substring in a string?

The function string.replace() only supports one string to get replaced. However, you might want to replace multiple chars or substrings in your target string.

For example, we may have the following original string:

orig_string = "JavaScript Programming language, CSharp Programmer, Python Unit Testing."

Now, you want to replace “JavaScript” with “Python” and “CSharp” with “Python”. To accomplish this, we have created a custom function.

"""
Function:
 Replace a list of many sub strings with a new one in original string.
"""
def replaceMany(orig_str, substring_list, new_str):
   # Traverse the substring list to replace
   for string in substring_list :
      # Test if string exists in the original string
      if string in orig_str :
         # Replace the string
         orig_str = orig_str.replace(string, new_str)
   return orig_str

Now, let’s invoke tour custom function by passing the desired parameters.

final_str = replaceMany(orig_string, ["JavaScript", "CSharp"], "Python")
print(final_str)

The output will come as:

Python Programming language, Python Programmer, Python Unit Testing.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Learn to interact with iFrame elements Learn to Interact with iFrame Elements
Next Article Multiple Ways to Iterate Strings in Python Iterate Strings in Python (5 Ways)

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x