4.1.10 Replacing Substrings: replace()

Unit: Unit 4: Strings, Lists, and Tuples • Interactive Practice

Quick Answer & Summary:

Interactive Python programming tutorial and practice in your browser.

Interactive Challenge (Run Live in Browser):

# Transform legacy protocol strings and sanitize template text
template = "Hello, {USER}! Welcome to {PLATFORM}. Enjoy {PLATFORM}!"

# 1. Replace template placeholders
step1 = template.replace("{USER}", "Alice")
final_message = step1.replace("{PLATFORM}", "PythonTeacher")

# 2. Limit replacements with the count argument
sample_log = "WARN: disk full. WARN: high CPU. WARN: memory leak."
single_fix = sample_log.replace("WARN", "CRITICAL", 1)

print("Message:", final_message)
print("Log:", single_fix)
Open in Live Interactive Python Sandbox →