Python Program to Replace a Character in a String
Beginner · Strings
This program replaces every copy of one character in a string with another, so "banana" with a replaced by o becomes "bonono". Strings cannot be changed in place, so the result is a new string.
Program
replace_character.py
text = "banana" # or: text = input("Enter a string: ")
old = "a" # or: old = input("Character to replace: ")
new = "o" # or: new = input("Replace it with: ")
result = text.replace(old, new)
print("Original string:", text)
print(f"After replacing '{old}' with '{new}':", result)
Output
Original string: banana After replacing 'a' with 'o': bonono
How it works
text.replace(old, new)returns a new string in which everyoldis changed tonew.- The original
textis not modified, because strings in Python are immutable. replace()is case-sensitive, so replacing "a" leaves any "A" alone.replace()also works on longer pieces of text, likereplace("cat", "dog").
Other ways to write it
Without replace()
Without replace()
text = "banana"
old, new = "a", "o"
result = ""
for ch in text:
if ch == old:
result += new
else:
result += ch
print(text, "->", result)
Output
banana -> bonono
The loop copies the string one character at a time and puts in new whenever it meets old.
Replace only the first one, or one position
Replace only the first one, or one position
text = "banana"
print("First 'a' only:", text.replace("a", "o", 1))
# Strings cannot be changed by index, so rebuild the string around position 2
pos = 2
print("Position 2 changed:", text[:pos] + "N" + text[pos + 1:])
Output
First 'a' only: bonana Position 2 changed: baNana
The third argument of replace() limits how many replacements are made. text[2] = "N" would raise a TypeError, so slicing builds the new string instead.
Try it yourself
Replace every space in "I love Python" with an underscore.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises