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: Python String Replace with Examples
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 BasicPython Tutorials

Python String Replace with Examples

Last updated: Apr 23, 2024 3:12 pm
By Meenakshi Agarwal
Share
6 Min Read
Define Python String Replace Method with Examples
Define Python String Replace Method with Examples
SHARE

String replacement is a common task in Python. A simple yet powerful way to replace a string in Python is by using the Python string replace() method. In today’s post, we’ll not only explain this method but will understand it from a practical point of view.

Contents
How to replace a string in PythonPython replace() method signatureExamplesExample 1: Using the module name to call replace()Example 2: Using the <str> object to call replace()

Python is one of the best scripting languages that most easily integrates with Selenium Webdriver for web-based automation, which requires a lot of string handling. There you may need to use string handling for building dynamic XPath, comparing dates, and searching for substrings. Hence, it’s inevitable to avoid using the Python string replace() method.

Replace String in Python with Examples

Nowadays, Python is also becoming popular for use in data analytics applications. Here you first need to process the data and then have to represent it in graphs. And, all such operations require string manipulation using methods like the Python string replace(). Next, apart from knowing about these methods, you also have to think creatively about using string functions. So, you can use them more efficiently.

In one of our earlier tutorials, we discussed Python Strings at great length. Perhaps you should read this post if you wish to learn strings from depth. However, to evaluate yourself for how logically you can use strings, please try this Python string quiz.

How to replace a string in Python

Often you’ll get to deal with a string (str object) in Python to modify its contents by replacing a part of the text with another.

In Python, everything is an object which is also true for strings. It means that str is a string object. And, Python’s string module provides a replace() method. We can call it in one of the following ways.

1- Calling replace() with the str object prefixing with a dot.
2- Call it directly after importing the string module.

Python replace() method signature

The <string.replace()> method has the following syntax.

str.replace(s, old, new[, replacefreq])

Here is a summary of the parameters passed to the method.

ParametersDescription
<s>It’s the value of a string to search and replace from.
<old>It’s the value of the old sub-string you like to replace.
<new>It’s the value of the new substring that you want to replace with the old one.
<replacefreq>It represents the number of times the string will get replaced.
String Replace method syntax

Examples

We have added two examples to showcase how to replace a string in Python. Copy the code from these into your IDE, have a deeper look, and run.

Example 1: Using the module name to call replace()

oldString = 'I love Python 2.0'

import string
 
newString = string.replace(oldString, '2.0', '3.0')
print(newString)
 
newString = string.replace(oldString, '2.0', '3.0.')
print(newString)
 
oldString = 'Are you a tester who tests websites? Be a good tester.'
newString = string.replace(oldString, 'test', 'develop', 1)
print(newString)

newString = string.replace(oldString, 'test', 'develop', 2)
print(newString)

newString = string.replace(oldString, 'test', 'develop', 3)
print(newString)

The above Python code will produce the following output.

I love Python 3.0
I love Python 3.0.
Are you a developer who tests websites? Be a good tester.
Are you a developer who develops websites? Be a good tester.
Are you a developer who develops websites? Be a good developer.

Example 2: Using the <str> object to call replace()

oldString = 'I love Python 2.0'
 
newString = oldString.replace('2.0', '3.0')
print(newString)
 
newString = oldString.replace('2.0', '3.0.')
print(newString)
 
oldString = 'Are you a tester who tests websites? Be a good tester.'
newString = oldString.replace('test', 'develop', 1)
print(newString)

newString = oldString.replace('test', 'develop', 2)
print(newString)

newString = oldString.replace('test', 'develop', 3)
print(newString)

Here is the execution report:

I love Python 3.0
I love Python 3.0.
Are you a developer who tests websites? Be a good tester.
Are you a developer who develops websites? Be a good tester.
Are you a developer who develops websites? Be a good developer.

From both of the above examples, it’s evident that you can use any of two methods to replace strings. Though, it’s the second method (in example 2) that is more convenient to use.

Must read – How to replace chars/substrings in Python string

Hopefully, the above post will have given you a fair idea of using the string replace() method in Python. You can learn more through practice, get the code from the examples, and start.

If you want us to cover any other topic in Python, then please write to us.

All the Best,

TechBeamers

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 Software Automation Testing Quiz for Dummies Software Automation Testing Quiz for Dummies
Next Article Selenium Webdriver Fluent Wait Command with Examples Understand Webdriver Fluent Wait with Examples

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