str.replace()
Python · Strings
Theory
.replace(old, new) returns a copy of the string in which every occurrence of the substring old is replaced by new. 'asha@techtown.in'.replace('techtown.in', 'company.com') gives 'asha@company.com'. An optional third argument limits how many replacements happen, scanning from the left: 'a-b-a'.replace('a', 'X', 1) gives 'X-b-a'. If old is not found, you simply get an unchanged copy back, with no error.
The match is exact and case-sensitive: replacing 'A' in 'a-b-a' changes nothing. Replacing with an empty string deletes text, which is a quick way to strip commas or currency symbols before converting ('1,200'.replace(',', '') then int()). Because strings are immutable, you must assign the result: text = text.replace(...). For pattern-based replacements, such as 'any run of digits', use re.sub() from the re module.
Why we use it
Cleaning text often means swapping one fixed piece for another: fixing a domain, removing thousands separators, replacing underscores with spaces. replace() does it in one call without loops or index math.
When to use it
Use replace() for fixed, literal substitutions. Chain calls for several fixes: s.replace(',', '').replace('Rs', ''). Use re.sub() when the text to replace follows a pattern or needs case-insensitive matching.
How it works
- Call s.replace(old, new, count)
- Scan the string from the left for old
- Found a match and count not reached? Yes: Write new in its place and keep scanning. No: Copy the rest unchanged.
- Build the result as a new string
- Return it; the original string is unchanged
Syntax
string.replace(old, new)Example
email = 'asha@techtown.in'
print(email.replace('techtown.in', 'company.com'))Key points
- Replaces ALL matches, not just the first, unless you pass a count
- Case-sensitive by default
- Returns a new string; assign it back to keep the change
- No error if the substring is not found
- Replace with '' to delete text, e.g. remove commas