• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Replace Characters in a String in Python

Replace Characters in a String in Python

Author: Aditya Raj
Last Updated: November 11, 2021

While working with text data in our programs, sometimes we may need to modify the data. In this article, we will look at various ways we can replace characters in a string in Python. We will discuss various use cases to understand the procedure in a better manner.

Table of Contents
  1. How to replace a character in a string?
  2. Replace all occurrences of a character in a string
  3. Replace first n occurrence of a character in a string
  4. Benefits of using the replace() method
  5. Conclusion

How to replace a character in a string?

To replace a character in a string with another character, we can use the replace() method. The replace() method when invoked on a string, takes the character to be replaced as first input, the new character as the second input and the number of characters to be replaced as an optional input. The syntax for the replace() method is as follows:

str.replace(old_character, new_character, n)

Here, old_character is the character that will be replaced with the new_character. The input n is the optional argument specifying the number of occurrences of old_character that has to be replaced with the new_character.

Let us now discuss how we can replace characters in a string using various use cases.

Replace all occurrences of a character in a string

To replace all the occurrences of a character with a new character, we simply have to pass the old character and the new character as input to the replace() method when it is invoked on the string. You can observe this in the following example.

input_string = "This is PythonForBeginners.com. Here, you   can read python tutorials for free."
new_string = input_string.replace('i', "I")
print("The original string is:")
print(input_string)
print("Output String is:")
print(new_string)

Output:

The original string is:
This is PythonForBeginners.com. Here, you   can read python tutorials for free.
Output String is:
ThIs Is PythonForBegInners.com. Here, you   can read python tutorIals for free.

Here, we have replaced all occurrences of the character ‘i’ with  the character ‘I’ using the replace() method.

We can also replace a group of consecutive characters with a new group of characters instead of replacing a single character. The syntax for replacing the group of consecutive characters remains unchanged. We just have to pass the old characters and new characters to the replace() method as follows.

input_string = "This is PythonForBeginners.com. Here, you   can read python tutorials for free."
new_string = input_string.replace('is', "IS")
print("The original string is:")
print(input_string)
print("Output String is:")
print(new_string)

Output:

The original string is:
This is PythonForBeginners.com. Here, you   can read python tutorials for free.
Output String is:
ThIS IS PythonForBeginners.com. Here, you   can read python tutorials for free.

In this example, you can see that we have replaced “is” with “IS” in the output string.

Replace first n occurrence of a character in a string

To replace the first n  occurrences of characters of a string with another character, we can specify the optional input argument in the replace() method. After specifying the number of  occurrences of the characters to be replaced, n occurrences of characters from the start of the string will be replaced.

For example, we can replace the first 3 occurrences of character ‘a’ in the given text with ‘A’ as follows.

input_string = "An owl sat on the back of an elephant and started to tease him."
new_string = input_string.replace('a', "A",3)
print("The original string is:")
print(input_string)
print("Output String is:")
print(new_string)

Output:

The original string is:
An owl sat on the back of an elephant and started to tease him.
Output String is:
An owl sAt on the bAck of An elephant and started to tease him.

Benefits of using the replace() method

Generally, we need to use regular expressions to find characters in a string to replace them. Regular expressions are hard to understand and need to be used carefully to match the characters that are to be replaced correctly. Moreover, Use of regular expressions is also computationally inefficient. Thus the replace() method gives us an easy and computationally efficient way to  replace characters in a string.

Conclusion

In this article, we have discussed the replace() method in Python. We have also seen the various ways in which we can use it to manipulate the text or staring data.  To learn more about python programming, you can read this article on list comprehension. You may also like this article on the linked list in Python.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us