Python String Replacement
Table of Contents
In the last lesson, we learned about Python String Searching. Now let’s replace words, fix typos, and clean up text.
Let’s Talk About Changing Text
We have a string. Maybe it is a message. Maybe it is a file path. Maybe it is user input. And we want to change a part of it.
Maybe we want to replace one word with another. Maybe we want to fix a typo. Maybe we want to remove something.
That is what string replacement is for.
Python gives us a few ways to do this. The most common is the replace() method. Let’s go through it.
The replace() Method in Python
The replace() method finds all occurrences of a substring and replaces them with something else.
text = "Hello, world!"new_text = text.replace("world", "Python")print(new_text)Output
Hello, Python!Here is what happened.
- We called
text.replace("world", "Python"). - It found “world” in the string.
- It replaced it with “Python”.
- It returned a new string with the change.
- The original
textis unchanged.
Let’s remember, strings are immutable. So replace() does not change the original. It creates a new string.
If we want to keep the change, we assign it to a variable.
text = text.replace("world", "Python")Now text is updated.
Replacing All Occurrences in Python
By default, replace() replaces all occurrences.
text = "one one one"new_text = text.replace("one", "two")print(new_text)Output
two two twoEvery “one” became “two”.
Limiting the Number of Replacements in Python
We can pass a third argument to limit how many replacements to make.
text = "one one one"new_text = text.replace("one", "two", 2)print(new_text)Output
two two oneOnly the first two occurrences were replaced. The third one stayed as “one”.
That is useful when we only want to change a specific number of things.
Replacing and Removing in Python
We can also use replace() to remove text. Just replace it with an empty string.
text = "Hello, world!"new_text = text.replace(",", "")print(new_text)Output
Hello world!The comma was removed. Because we replaced it with "", which is an empty string.
That is a common way to clean up text.
Case Sensitivity in Python String Replacement
replace() is case sensitive.
text = "Hello, world!"new_text = text.replace("hello", "Hi")print(new_text)Output
Hello, world!Nothing changed. Because “hello” with a lowercase h is not the same as “Hello” with a capital H.
If we want to ignore case, we have to do it manually. One way is to convert the string to lowercase first, then replace, but that changes the whole string.
For case-insensitive replacement, we might need regular expressions. We will cover that later.
Chaining Replacements in Python
We can chain multiple replace() calls together.
text = "Hello, world!"new_text = text.replace("Hello", "Hi").replace("world", "Python")print(new_text)Output
Hi, Python!It works from left to right. First replace “Hello” with “Hi”. Then replace “world” with “Python”.
We can chain as many as we want. But too many becomes hard to read.
Python String Replacement: A Real-Life Example
Let’s clean up a phone number.
phone = "(123) 456-7890"cleaned = phone.replace("(", "").replace(")", "").replace("-", "").replace(" ", "")print(cleaned)Output
1234567890That removes all the formatting characters. Now we have a clean number.
Another Example — Fixing a File Path
path = "C:\\Users\\Alex\\Documents\\file.txt"new_path = path.replace("\\", "/")print(new_path)Output
C:/Users/Alex/Documents/file.txtThat converts backslashes to forward slashes. Useful when moving between Windows and Unix-style paths.
Using translate() for Multiple Replacements in Python
If we need to replace many single characters at once, translate() can be faster.
text = "Hello, world!"table = str.maketrans("lo", "LO")new_text = text.translate(table)print(new_text)Output
HeLLO, wOrLd!Wait. Let me explain.
str.maketrans("lo", "LO") creates a translation table. It maps ‘l’ to ‘L’, and ‘o’ to ‘O’.
Then text.translate(table) applies that mapping. Every ‘l’ becomes ‘L’. Every ‘o’ becomes ‘O’.
So “Hello, world!” becomes “HeLLO, wOrLd!”.
That is a quick way to do character-level replacements. It is faster than multiple replace() calls when we have many characters.
Replacing with a Regular Expression in Python
For more complex patterns, we can use the re module. That is regular expressions. We will cover that in a later article. But just so we know, re.sub() is the replacement function there.
import retext = "Hello, world!"new_text = re.sub(r"world", "Python", text)print(new_text)Output
Hello, Python!That does the same as replace() in this simple case. But regular expressions can do much more complex patterns.
Common Mistakes with Python String Replacement
Mistake 1: Forgetting to Assign the Result
text = "Hello"text.replace("H", "J")print(text)Output
HelloBecause replace() returns a new string. It does not change the original. We have to assign it.
So what do we do? We assign the result.
text = text.replace("H", "J")print(text)Output
JelloMistake 2: Expecting Case-Insensitive Replacement
text = "Hello"text = text.replace("hello", "Hi")print(text)Output
HelloBecause it is case sensitive. So what do we do? We use .lower() or regular expressions if we need case-insensitive.
Mistake 3: Using the Wrong Order of Arguments
text = "Hello"text = text.replace("H", "J") # Correct: old, newThe first argument is what to find. The second is what to replace it with. Let’s not mix them up.
Mistake 4: Thinking replace() Changes the Original
We already covered this. But it is worth repeating. replace() returns a new string. The original is untouched.
A Real-Life Example with User Input
Let’s sanitize user input by removing unwanted characters.
user_input = input("Enter something: ")cleaned = user_input.replace("<", "").replace(">", "").replace("&", "")print(f"Cleaned: {cleaned}")That removes angle brackets and ampersands. A simple way to prevent some injection attacks.
Next, we will learn about Python Regular Expressions and search text using flexible patterns.