Python replace string
last modified November 18, 2026 Python 3.15
In this article we show how to replace strings in Python.
Python strings are immutable. Every replacing operation returns a new string and leaves the original unchanged. There are several ways of replacing strings in Python:
- the
replacemethod for plain substrings, - the
translatemethod for single characters, - the
re.subandre.subnfunctions for regular expression patterns, - slicing,
removeprefix, andremovesuffixfor replacing at a position.
The replace method
The replace method returns a copy of the string with
occurrences of a substring replaced by another substring.
str.replace(old, new, count=-1)
The old parameter is the substring to be replaced, new
is its replacement, and the optional count limits the number of
replacements. The default of -1 replaces all occurrences.
msg = 'There is a fox in the forest. The fox has red fur.'
msg2 = msg.replace('fox', 'wolf')
print(msg2)
print(msg)
Both occurrences of the word fox are replaced with wolf. The original string is not modified.
$ python replace_fun.py There is a wolf in the forest. The wolf has red fur. There is a fox in the forest. The fox has red fur.
Limiting the number of replacements
The count argument limits how many occurrences are replaced,
counting from the left. Since Python 3.13, count can also be
passed as a keyword argument.
msg = 'There is a fox in the forest. The fox has red fur.'
print(msg.replace('fox', 'wolf', 1))
print(msg.replace('fox', 'wolf', count=1))
print(msg.replace('fox', 'wolf', -1))
print(msg.replace('dog', 'wolf'))
data = '1,2,3,4,5'
print(data.replace(',', ''))
print(data.replace('', '-'))
With a count of 1, only the first fox is replaced. A negative count replaces everything. If the substring is not found, the method returns an unchanged copy; it never raises an error.
print(data.replace(',', ''))
print(data.replace('', '-'))
Replacing with an empty string deletes the substring. Replacing an empty string inserts the new string between every two characters and at both ends.
$ python replace_count.py There is a wolf in the forest. The fox has red fur. There is a wolf in the forest. The fox has red fur. There is a wolf in the forest. The wolf has red fur. There is a fox in the forest. The fox has red fur. 12345 -1-,-2-,-3-,-4-,-5-
Replacing the last occurrence
There is no built-in method that replaces from the right. We can use
rpartition, rsplit, or rfind.
msg = 'There is a fox in the forest. The fox has red fur.' old, new = 'fox', 'wolf' head, sep, tail = msg.rpartition(old) print(head + new + tail if sep else msg) print(new.join(msg.rsplit(old, 1))) idx = msg.rfind(old) print(msg[:idx] + new + msg[idx + len(old):])
The example shows three ways of replacing the last fox.
head, sep, tail = msg.rpartition(old) print(head + new + tail if sep else msg)
The rpartition method splits the string at the last occurrence
of the separator and returns a three-element tuple. If the separator is not
found, sep is an empty string, and we keep the message unchanged.
print(new.join(msg.rsplit(old, 1)))
rsplit with a maximum of one split cuts the string at the last
occurrence; joining the two parts with the new word puts it in place of the
old one.
idx = msg.rfind(old) print(msg[:idx] + new + msg[idx + len(old):])
The rfind method returns the index of the last occurrence, or -1
when the substring is missing; this case would need its own check. We build
the new string with slicing. Note that the end of the old word is computed
from the length of the old word, not the new one.
$ python replace_last.py There is a fox in the forest. The wolf has red fur. There is a fox in the forest. The wolf has red fur. There is a fox in the forest. The wolf has red fur.
Chaining replace calls
Since replace returns a string, we can chain the calls to do
several replacements.
msg = 'There is a fox in the forest. The fox has red fur.'
msg2 = msg.replace('fox', 'wolf').replace('red', 'brown').replace('fur', 'legs')
print(msg2)
In the example, we perform three replacements; each call works on the result of the previous one.
$ python chaining.py There is a wolf in the forest. The wolf has brown legs.
Multiple replacements at once
Sequential replacements can interfere with each other: a later replacement also sees the text produced by an earlier one.
import re
msg = 'The cat chased the dog. The dog chased the cat.'
swaps = {'cat': 'dog', 'dog': 'cat'}
res = msg
for old, new in swaps.items():
res = res.replace(old, new)
print(res)
pattern = re.compile('|'.join(map(re.escape, swaps)))
print(pattern.sub(lambda m: swaps[m.group()], msg))
We want to swap cats and dogs. The loop first turns every cat into a dog and then every dog, including the new ones, into a cat.
pattern = re.compile('|'.join(map(re.escape, swaps)))
print(pattern.sub(lambda m: swaps[m.group()], msg))
A single regular expression pass solves the problem. We build an alternation
of the escaped keys, cat|dog, and let a function look up the
replacement for each match. Each part of the text is replaced at most once.
$ python multiple.py The cat chased the cat. The cat chased the cat. The dog chased the cat. The cat chased the dog.
Replacing characters with translate
The translate method replaces single characters using a
translation table, which is created with str.maketrans. It is
the fastest way to replace or delete many different characters.
msg = 'There is a fox in the forest. The fox has red fur.'
print(msg.translate(str.maketrans('.', '!')))
table = str.maketrans('aeiou', 'AEIOU')
print(msg.translate(table))
table = str.maketrans({'.': ' (end)', 'f': 'F', ' ': None})
print(msg.translate(table))
table = str.maketrans('', '', 'aeiou')
print(msg.translate(table))
With two strings of equal length, maketrans maps each character
of the first string to the character at the same position in the second.
table = str.maketrans({'.': ' (end)', 'f': 'F', ' ': None})
A dictionary maps characters to strings of any length, or to
None, which deletes the character.
table = str.maketrans('', '', 'aeiou')
The third argument lists the characters to delete.
$ python translating.py There is a fox in the forest! The fox has red fur! ThErE Is A fOx In thE fOrEst. ThE fOx hAs rEd fUr. ThereisaFoxintheForest (end)TheFoxhasredFur (end) Thr s fx n th frst. Th fx hs rd fr.
Replacing with re.sub
The re.sub function replaces matches of a regular expression
pattern.
re.sub(pattern, repl, string, count=0, flags=0)
It returns the string obtained by replacing the leftmost non-overlapping
occurrences of the pattern by repl. We have a small text file
to work with.
The Battle of Thermopylae was fought between an alliance of Greek city-states, led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the course of three days, during the second Persian invasion of Greece.
The text contains commas, dots, and newlines.
import re
with open('thermopylae.txt', encoding='utf-8') as f:
text = f.read()
cleaned = re.sub(r'[.,]', '', text)
words = sorted(set(cleaned.split()), key=str.lower)
print(len(words))
print(words)
print(re.sub(r'\s+', ' ', text).strip())
We remove punctuation, collect the unique words, and normalize whitespace.
cleaned = re.sub(r'[.,]', '', text)
The character class matches a dot or a comma; we replace them with an empty
string. Inside a class, the dot is a literal character. We always write
patterns as raw strings: in a normal string literal, '\.' is an
invalid escape sequence and produces a SyntaxWarning.
words = sorted(set(cleaned.split()), key=str.lower)
A set has no order, so we sort the unique words, ignoring case.
print(re.sub(r'\s+', ' ', text).strip())
Every run of whitespace characters, including newlines, is replaced with a single space.
$ python replace_reg.py 30 ['alliance', 'an', 'and', 'Battle', 'between', 'by', 'city-states', 'course', 'days', 'during', 'Empire', 'fought', 'Greece', 'Greek', 'I', 'invasion', 'King', 'led', 'Leonidas', 'of', 'over', 'Persian', 'second', 'Sparta', 'The', 'the', 'Thermopylae', 'three', 'was', 'Xerxes'] The Battle of Thermopylae was fought between an alliance of Greek city-states, led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the course of three days, during the second Persian invasion of Greece.
Backreferences in the replacement
The replacement string can refer to the groups captured by the pattern.
import re
dates = 'Released 2024-01-29, updated 2026-11-18.'
print(re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\3.\2.\1', dates))
print(re.sub(r'(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})', r'\g<d>/\g<m>/\g<y>', dates))
print(re.sub(r'(\d+)', r'<\g<1>0>', 'a 1 b 2'))
We change the format of dates. \1, \2, and
\3 refer to the numbered groups, \g<name> to
named groups.
print(re.sub(r'(\d+)', r'<\g<1>0>', 'a 1 b 2'))
The \g<1> form is needed when a digit follows the group
reference; \10 would mean group number ten.
$ python backrefs.py Released 29.01.2024, updated 18.11.2026. Released 29/01/2024, updated 18/11/2026. a <10> b <20>
Replacement function
Instead of a string, we can pass a function. It receives a match object and returns the replacement text.
import re
msg = 'apples 3, pears 12, plums 7'
def double(m):
return str(int(m.group()) * 2)
print(re.sub(r'\d+', double, msg))
prices = {'apples': 1.2, 'pears': 0.8}
print(re.sub(r'\b[a-z]+\b', lambda m: f'{m[0]} ({prices.get(m[0], "?")} €)', msg))
The double function doubles every number. The lambda looks up
the price of each fruit name in a dictionary; m[0] is the same
as m.group(), the whole match.
$ python callable_repl.py apples 6, pears 24, plums 14 apples (1.2 €) 3, pears (0.8 €) 12, plums (? €) 7
Counting replacements with re.subn
The re.subn function works like re.sub, but
returns a tuple with the new string and the number of replacements made.
import re
msg = 'There is a fox in the forest. The fox has red fur.'
res, n = re.subn(r'\bfox\b', 'wolf', msg)
print(res)
print(f'{n} replacements')
print(re.sub(r'fox', 'wolf', msg, count=1))
The \b word boundaries make sure that only the whole word fox is
replaced. The count argument of re.sub should be
passed by keyword; passing it positionally is deprecated since Python 3.13.
$ python subn_fun.py There is a wolf in the forest. The wolf has red fur. 2 replacements There is a wolf in the forest. The fox has red fur.
Case-insensitive replacement
The replace method is case-sensitive. For case-insensitive
replacements, we use re.sub with the
re.IGNORECASE flag.
import re
msg = 'Fox, fox, FOX and foxes.'
print(msg.replace('fox', 'wolf'))
print(re.sub(r'fox', 'wolf', msg, flags=re.IGNORECASE))
print(re.sub(r'\bfox\b', 'wolf', msg, flags=re.I))
The plain replace changes only the lowercase fox, including the
one inside foxes. With re.IGNORECASE (or its short form
re.I), all variants are replaced; word boundaries keep foxes
intact.
$ python ignore_case.py Fox, wolf, FOX and wolfes. wolf, wolf, wolf and wolfes. wolf, wolf, wolf and foxes.
Replacing by position
Strings do not support item assignment. To replace a character at a given position, we build a new string with slicing, or go through a list.
word = 'forest'
try:
word[0] = 'F'
except TypeError as e:
print(e)
print('F' + word[1:])
print(word[:2] + 'X' + word[3:])
chars = list(word)
chars[-1] = 'T'
print(''.join(chars))
Slicing is the usual way for a single change. For many changes at different positions, we convert the string to a list of characters, modify the list, and join it back.
$ python replace_index.py 'str' object does not support item assignment Forest foXest foresT
Removing a prefix or suffix
The removeprefix and removesuffix methods remove
an exact prefix or suffix if it is present.
fname = 'report_draft.txt'
print(fname.removeprefix('report_'))
print(fname.removesuffix('.txt') + '.md')
print('notes.txt'.removeprefix('report_'))
print('xxhelloxx'.strip('x'))
print('txt.data.txt'.strip('.txt'))
print('txt.data.txt'.removesuffix('.txt'))
If the prefix is not there, the string is returned unchanged. The methods are
often confused with strip, lstrip, and
rstrip, which treat their argument as a set of characters:
strip('.txt') removes all leading and trailing dots, t's, and
x's, which eats the start of txt.data.
$ python prefix_suffix.py draft.txt report_draft.md notes.txt hello data txt.data
Replacing bytes
The bytes and bytearray types have their own
replace method that works with bytes arguments.
data = b'name=John&age=34&city=Bratislava'
print(data.replace(b'&', b'\n').decode())
try:
data.replace('&', '\n')
except TypeError as e:
print(e)
We replace the & separators with newlines. Mixing bytes and
str arguments raises a TypeError.
$ python replace_bytes.py name=John age=34 city=Bratislava a bytes-like object is required, not 'str'
Replacing text in a file
Files cannot be edited in place like strings in memory. We read the whole contents, replace the text, and write the result back.
from pathlib import Path
path = Path('thermopylae.txt')
text = path.read_text(encoding='utf-8')
path.write_text(text.replace('Persian', 'Achaemenid'), encoding='utf-8')
print(path.read_text(encoding='utf-8'), end='')
The read_text and write_text methods of
pathlib.Path open and close the file for us. For large files, we
would process the file line by line and write to a new file instead. The
example overwrites the original file, so we keep a backup of important data.
$ python replace_file.py The Battle of Thermopylae was fought between an alliance of Greek city-states, led by King Leonidas of Sparta, and the Achaemenid Empire of Xerxes I over the course of three days, during the second Achaemenid invasion of Greece.
Source
str.replace – Python documentation
In this article we have replaced strings in Python. See also Python regular expressions, Python split string, Python add string, and Python string.
Author
List all Python tutorials.