Replace a Character in a String Dry Run in PYTHON

Replace a Character in a String is an interactive PYTHON dry run visualizer from the Strings programs section. Study the source code, then use the execution controls to follow each step, variable update, highlighted line, and console output.

This page provides a browser-based dry run with source-code highlighting, auto-scroll, voice narration controls, and execution output for learning the program step by step.

Replace a Character in a String Program Code

# Python program to replace a character in a string
text = "banana"
old_char = 'a'
new_char = 'o'

# Method 1: Using replace() method
result1 = text.replace(old_char, new_char)

# Method 2: Using list comprehension
result2 = "".join([new_char if char == old_char else char for char in text])

# Method 3: Using translate() for multiple replacements
translation_table = str.maketrans({old_char: new_char})
result3 = text.translate(translation_table)

print("Original:", text)
print("After replacement (replace):", result1)
print("After replacement (list comp):", result2)
print("After replacement (translate):", result3)

View the complete Strings programs page.

Program Console Replace a Character in a String Topic: PYTHON Vignaankosh.com
Execution Panel
Step 0/0
Console is empty.