Content · Programming · Python

Python str.replace Method: Usage and Examples

str.replace(old, new, count=-1) returns a string where occurrences of old are replaced with new. The optional count limits how many replacements occur from left to right. Learn with a clear example and common mistakes.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

This guide explains str.replace Method: Usage and Examples through a focused example and practical reasoning. No prior knowledge of this specific operation is required.

Understanding the Concept


str.replace(old, new, count=-1) returns a string where occurrences of old are replaced with new. The optional count limits how many replacements occur from left to right.

When You Would Use This


Change only the first separator in a structured status line.

Step-by-Step Example


status_line = "ready|queued|done"
print(status_line.replace("|", ": ", 1))
print(status_line.replace("|", " / "))

How the Example Works


The first call replaces only the first pipe. The second replaces every pipe. Neither call changes the original string object.

Example Output


ready: queued|done
ready / queued / done

Try It Yourself


Replace at most two spaces with underscores and compare with replacing all spaces.

Common Beginner Mistakes


  • Forgetting that replacement is case-sensitive.
  • Assuming the method mutates a string in place.
  • Using arbitrary replacement rules for parsing complex CSV or HTML data.

Key Takeaways


  • str.replace(old, new, count=-1) returns a string where occurrences of old are replaced with new.
  • The first call replaces only the first pipe.
  • Avoid this mistake: Forgetting that replacement is case-sensitive.
Share this resourceSend this page to someone who may find it useful.