How to Replace Characters in a String in Python

Learn how to replace characters or substrings in Python strings. Master the replace() method, count limits, and using translate for multiple characters.

Try Code in Editor

Explanation

String manipulation is at the heart of parsing inputs, rendering templates, cleansing data, and generating output text. In Python, modifying specific characters or substrings inside a text block is straightforward, but it requires understanding a fundamental property of strings: immutability.

Because Python strings are immutable, you cannot modify their characters in-place (e.g., writing `text[0] = "A"` raises a `TypeError`). Instead, any operation that alters a string must create and return a brand-new string. The primary tool for this is the built-in `.replace()` method.

The `.replace(old, new)` method searches a string for all occurrences of a specified substring and replaces them with a new substring. You can also specify an optional third argument `count`, which limits the number of replacements to perform from left to right. For more complex, multi-character replacements, you can use the `.translate()` method or regular expressions with the `re.sub()` function.

Step-by-Step Implementation

  1. 1

    Call the .replace() method on the target string.

  2. 2

    Pass the target substring as the first argument, and the replacement as the second.

  3. 3

    Use the count argument if you want to restrict the number of replacements.

Code Example

This script demonstrates modifying strings by replacing substrings and characters using the replace() method.

replace_chars.py
Try in Editor
text = "banana apple banana cherry"

# 1. Replace all occurrences of a word
replaced_all = text.replace("banana", "orange")
print("Replaced all:", replaced_all)

# 2. Replace with a count limit (only first occurrence)
replaced_limit = text.replace("banana", "orange", 1)
print("Replaced limit:", replaced_limit)

# 3. Replace individual characters (immutability demonstration)
phrase = "pyth0n"
corrected = phrase.replace("0", "o")
print("Corrected string:", corrected)
Terminal Output
Replaced all: orange apple orange cherry
Replaced limit: orange apple banana cherry
Corrected string: python

Frequently Asked Questions

How do I replace characters in a string in-place?

You cannot because Python strings are immutable. You must assign the result of the .replace() method back to your string variable: text = text.replace(...).

Is replace() case-sensitive?

Yes, .replace() is strictly case-sensitive. To perform case-insensitive replacements, you must use regular expressions with the re module and re.IGNORECASE.

Related How-To Guides

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.