Programming
Text Editing
String Manipulation
Coding Tutorial
Python

How to remove text from a string?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Removing text from a string sounds simple, but the correct method depends on what exactly you want to remove. A fixed substring, a single character range, and a pattern such as all digits are different problems, and each has a different clean solution.

Remove a Fixed Substring

If you know the exact text you want to remove, direct replacement is the simplest approach. In Python, strings are immutable, so removal means creating a new string with the target text replaced by an empty string.

python
text = "Hello, World!"
cleaned = text.replace("World", "")
print(cleaned)

Output:

text
Hello, !

This works well when the target is literal and known in advance. It removes every occurrence by default.

Remove Only the First Match

Sometimes you only want to remove the first occurrence.

python
text = "apple apple banana"
cleaned = text.replace("apple", "", 1)
print(cleaned)

Output:

text
 apple banana

That third argument is useful when later matches should stay intact.

Remove by Position Instead of by Value

If you know where the text lives rather than what it says, slicing is clearer than replacement.

python
text = "Error: 404"
cleaned = text[:7] + text[10:]
print(cleaned)

Output:

text
Error:

Slicing is precise, but it assumes you already know the indexes. It is best when the string format is fixed.

Remove a Pattern With Regular Expressions

When the text varies, regular expressions are often the right tool. For example, if you need to remove all digits, a literal replace call is not enough.

python
1import re
2
3text = "Order 123 shipped on 2026-03-11"
4cleaned = re.sub(r"\d+", "", text)
5print(cleaned)

Output:

text
Order  shipped on --

Regex is powerful, but it should be used only when a literal method is not expressive enough. Simpler code is usually easier to maintain.

Removing Whole Words Safely

A common mistake is removing a word with replace and accidentally changing part of another word. For example, removing cat from concatenate is probably not intended.

Use word boundaries if you want whole-word removal.

python
1import re
2
3text = "cat scatter category cat"
4cleaned = re.sub(r"\bcat\b", "", text)
5print(cleaned)

Output:

text
 scatter category 

Removing Extra Spaces After Cleanup

Text removal often leaves awkward spaces or punctuation. It is usually worth doing a second pass to normalize whitespace.

python
1import re
2
3text = "cat scatter category cat"
4cleaned = re.sub(r"\bcat\b", "", text)
5cleaned = re.sub(r"\s+", " ", cleaned).strip()
6print(cleaned)

Output:

text
scatter category

This two-step pattern is common in data cleaning pipelines.

A Reusable Helper

If you do this often, wrap the behavior in a small function so the calling code stays readable.

python
1import re
2
3
4def remove_text(text: str, target: str, whole_word: bool = False) -> str:
5    if whole_word:
6        pattern = rf"\b{re.escape(target)}\b"
7        return re.sub(pattern, "", text)
8    return text.replace(target, "")
9
10
11print(remove_text("red apple and green apple", "apple"))
12print(remove_text("cat scatter category cat", "cat", whole_word=True))

Common Pitfalls

The most common pitfall is using replace when the task is really pattern matching. If you need to remove variable formats such as numbers, dates, or HTML tags, use regex or a parser.

Another mistake is forgetting that strings are immutable. Methods like replace return a new string. They do not modify the original variable in place.

Developers also often ignore whitespace cleanup. Removing text is only half the job if the result still contains doubled spaces or stray punctuation.

Summary

  • Use replace for known literal substrings.
  • Use the third argument of replace when only the first few matches should be removed.
  • Use slicing when removal is based on character position.
  • Use re.sub for variable or structured patterns.
  • Normalize whitespace after removal if presentation matters.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.