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:

 
 

Comments and Discussions!

Load comments ↻





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