py4u blog

Python - Replace all words except the given word

In Python, there are often scenarios where you need to manipulate text by replacing all words in a string while keeping specific words intact. This can be useful in various applications, such as text anonymization, data cleaning, or custom text formatting. In this blog post, we will explore different approaches to achieve this task, including using regular expressions and simple string manipulation techniques.

2026-06

Table of Contents#

  1. Problem Statement
  2. Method 1: Using Regular Expressions
  3. Method 2: Using String Manipulation
  4. Common Practices and Best Practices
  5. Example Usage
  6. Conclusion
  7. References

1. Problem Statement#

The problem we aim to solve is to replace all words in a given string with a specified replacement word, except for a given list of words that should remain unchanged. For example, if our text is "The quick brown fox jumps over the lazy dog", and the words to keep are "fox" and "dog", and the replacement word is "X", the output should be "X X X fox X X X X dog".

2. Method 1: Using Regular Expressions#

Regular expressions provide a powerful and flexible way to match and replace patterns in text. We can use the re module in Python to achieve our goal.

import re
 
def replace_except(text, keep_words, replacement):
    # Create a regular expression pattern to match words
    pattern = r'\b(?!(?:' + '|'.join(re.escape(word) for word in keep_words) + r')\b)\w+\b'
    return re.sub(pattern, replacement, text)
 
# Example usage
text = "The quick brown fox jumps over the lazy dog"
keep_words = ["fox", "dog"]
replacement = "X"
result = replace_except(text, keep_words, replacement)
print(result)

Explanation#

  • r'\b(?!(?:' + '|'.join(re.escape(word) for word in keep_words) + r')\b)\w+\b': This is the regular expression pattern.
    • \b represents a word boundary.
    • (?!...) is a negative lookahead assertion, which means the pattern inside it should not match.
    • (?:' + '|'.join(re.escape(word) for word in keep_words) + r') creates a group of words to keep, separated by | (OR).
    • \w+ matches one or more word characters.
  • re.sub(pattern, replacement, text) replaces all occurrences of the pattern in the text with the replacement string.

3. Method 2: Using String Manipulation#

We can also solve this problem without using regular expressions by splitting the text into words and checking each word against the list of words to keep.

def replace_except_string_manipulation(text, keep_words, replacement):
    words = text.split()
    result_words = []
    for word in words:
        if word in keep_words:
            result_words.append(word)
        else:
            result_words.append(replacement)
    return ' '.join(result_words)
 
# Example usage
text = "The quick brown fox jumps over the lazy dog"
keep_words = ["fox", "dog"]
replacement = "X"
result = replace_except_string_manipulation(text, keep_words, replacement)
print(result)

Explanation#

  • text.split() splits the text into a list of words.
  • We iterate through each word in the list. If the word is in the list of words to keep, we add it to the result_words list. Otherwise, we add the replacement word.
  • ' '.join(result_words) joins the list of words back into a string, separated by a space.

4. Common Practices and Best Practices#

  • Case Sensitivity: Both methods are case-sensitive by default. If you want to perform a case-insensitive replacement, you can convert both the text and the list of words to keep to the same case (e.g., all lowercase) before processing.
  • Regular Expressions: When using regular expressions, make sure to escape special characters in the words to keep using re.escape(). This ensures that the words are treated as literal strings.
  • Performance: For simple cases, string manipulation may be faster than regular expressions. However, regular expressions are more powerful and can handle more complex patterns.

5. Example Usage#

Let's consider a more practical example. Suppose we have a text containing user names and we want to anonymize all words except for a list of approved names.

text = "John went to the store with Mary. They met David there."
approved_names = ["John", "Mary"]
replacement = "USER"
result = replace_except(text, approved_names, replacement)
print(result)

This will output: "John USER USER USER USER Mary. USER USER David USER".

6. Conclusion#

In this blog post, we have explored two different methods to replace all words in a string except for a given list of words in Python. Regular expressions provide a powerful and flexible solution, while string manipulation is a simpler and more straightforward approach. The choice between the two methods depends on the complexity of the problem and the performance requirements.

7. References#