Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Python Dictionary

  1. Home
  2. Python Dictionary
  3. str.replace() / str.translate()

str.replace() / str.translate()

Methods for replacing specific characters or substrings within a string with another string. You can also perform fast bulk replacement using a translation table.

Syntax

# Replaces all occurrences of old with new in the string (returns a new string).
str.replace(old, new, count=-1)

# Creates a translation table for multi-character substitution.
str.maketrans(x, y=None, z=None)

# Replaces characters using a translation table created with maketrans().
str.translate(table)

Method List

MethodDescription
str.replace(old, new, count=-1)Replaces occurrences of old with new in the string. If count is specified, at most count replacements are made from the left. The original string is not modified.
str.maketrans(x, y, z)Creates a translation table (dictionary) for use with translate(). Passing x and y creates a one-to-one character mapping; passing z maps each character in that string to None (deletion).
str.translate(table)Translates or deletes characters based on the table created by maketrans().

Sample Code

str_replace_basic.py
# Replace a substring using replace().
text = "Python is hard. Let's learn Python. Python is wonderful."
result = text.replace("hard", "fun")
print(result)

# Limit the number of replacements with count.
text2 = "a b c a b c a"
print(text2.replace("a", "X", 2))

# To delete characters, replace them with an empty string.
html_like = "Hello, <b>Gojo Satoru</b>!"
clean = html_like.replace("<b>", "").replace("</b>", "")
print(clean)

Running the code produces the following output:

python3 str_replace_basic.py
Python is fun. Let's learn Python. Python is wonderful.
X b c X b c a
Hello, Gojo Satoru!
str_replace_translate.py
# Use maketrans() and translate() to convert multiple characters at once.
# Convert lowercase vowels to uppercase (a simple character mapping).
vowel_table = str.maketrans("aeiou", "AEIOU")
print("hello world".translate(vowel_table))

# ROT13-style shift: map a-m to n-z and n-z to a-m.
rot13_table = str.maketrans(
    "abcdefghijklmnopqrstuvwxyz",
    "nopqrstuvwxyzabcdefghijklm"
)
print("hello".translate(rot13_table))

# Delete specific characters (characters in the third argument are removed).
remove_table = str.maketrans("", "", "aeiou")
print("hello world".translate(remove_table))

# You can also specify a translation table using a dictionary (with Unicode code points).
table2 = str.maketrans({"A": "1", "B": "2", "C": "3"})
print("ABCABC".translate(table2))

Running the code produces the following output:

python3 str_replace_translate.py
hEllO wOrld
uryyb
hll wrld
123123
str_replace_practical.py
# replace() does not modify the original string (strings are immutable).
original = "hello"
new = original.replace("l", "r")
print(original)
print(new)

# A practical example: normalize mixed line endings.
mixed_newlines = "line1\r\nline2\rline3\nline4"
unified = mixed_newlines.replace("\r\n", "\n").replace("\r", "\n")
print(repr(unified))

Running the code produces the following output:

python3 str_replace_practical.py
hello
herro
'line1\nline2\nline3\nline4'

Common Mistakes

Common Mistake 1: Forgetting to assign the result of replace()

Python strings are immutable — they cannot be changed in place. replace() returns a new string with the replacements applied. If you don't capture the return value, the replacement has no effect.

mistake1_ng.py
text = "Python is hard"

# The return value is discarded — no effect
text.replace("hard", "fun")
print(text)

Running the code produces the following output:

python3 mistake1_ng.py
Python is hard
mistake1_ok.py
text = "Python is hard"

# Reassign the result to update the variable.
text = text.replace("hard", "fun")
print(text)

Running the code produces the following output:

python3 mistake1_ok.py
Python is fun

Common Mistake 2: Unequal lengths in maketrans() arguments

When passing two strings to str.maketrans(x, y), both must have the same length. If they differ, a ValueError is raised.

mistake2_ng.py
# x and y have different lengths
table = str.maketrans("aeiou", "AEIO")
print("hello".translate(table))

Running the code produces the following output:

python3 mistake2_ng.py
ValueError: the first two maketrans arguments must have equal length
mistake2_ok.py
# x and y must be the same length.
table = str.maketrans("aeiou", "AEIOU")
print("hello".translate(table))

Running the code produces the following output:

python3 mistake2_ok.py
hEllO

Notes

Python strings are immutable (cannot be changed in place). replace() does not modify the original string — it returns a new string object with the replacements applied. To update the original variable, reassign it: text = text.replace(old, new).

When replacing multiple substrings in sequence, chaining replace() calls (method chaining) is the common approach. However, when the number of replacements is large, translate() is faster. For text cleansing — bulk deletion or conversion of unwanted characters — translate() is particularly effective.

For advanced pattern matching and replacement using regular expressions, use re.sub() from the standard library's re module. For example, to collapse consecutive whitespace into a single space, use re.sub(r"\s+", " ", text). For string searching, see str.find() / str.index().

If you find any errors or copyright issues, please .