×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python - Replace all Instances of a Single Character in a String

By IncludeHelp Last updated : April 21, 2024

Problem statement

Given a string, write a Python program to replace all instances of a single character.

Replacing all instances of a single character in a string

To replace all instances of a single character, use the string.replace() method and pass the single character to replace as the first parameter and the character or string as the second parameter to be replaced with.

Python program to replace all instances of a single character in a string

string = "Hello World!"

# Replace all instances of 'o' with 'x'
result = string.replace("o", "x")

print("Original string :", string)
print("Updated string :", result)

# Replace all instances of 'o' with 'ABC'
result = string.replace("o", "ABC")

print("Original string :", string)
print("Updated string :", result)

Output

Original string : Hello World!
Updated string : Hellx Wxrld!
Original string : Hello World!
Updated string : HellABC WABCrld!

To understand the above program, you should have the basic knowledge of the following Python topics:

 
 
Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.