Last modified: Nov 08, 2024 By Alexander Williams

Python re.subn: Pattern Replacement with Count Information

The re.subn() function in Python is similar to re.sub, but it provides additional information about the number of substitutions made.

Basic Syntax and Usage

The function returns a tuple containing the modified string and the count of substitutions performed. Here's the basic syntax:


import re
text = "apple apple orange"
new_text, count = re.subn(r'apple', 'banana', text)
print(f"Modified text: {new_text}")
print(f"Number of replacements: {count}")


Modified text: banana banana orange
Number of replacements: 2

Using Count Parameter

You can limit the number of replacements using the count parameter:


text = "apple apple apple orange"
new_text, count = re.subn(r'apple', 'banana', text, count=2)
print(f"Modified text: {new_text}")
print(f"Number of replacements: {count}")


Modified text: banana banana apple orange
Number of replacements: 2

Working with Regular Expressions

Like re.search and re.findall, re.subn() supports complex pattern matching:


text = "Date: 2023-01-15 and 2023-02-20"
new_text, count = re.subn(r'\d{4}-\d{2}-\d{2}', 'DATE', text)
print(f"Modified text: {new_text}")
print(f"Number of replacements: {count}")


Modified text: Date: DATE and DATE
Number of replacements: 2

Using Function as Replacement

You can pass a function to transform matched patterns:


def uppercase_match(match):
    return match.group(0).upper()

text = "hello world hello"
new_text, count = re.subn(r'hello', uppercase_match, text)
print(f"Modified text: {new_text}")
print(f"Number of replacements: {count}")


Modified text: HELLO world HELLO
Number of replacements: 2

Case-Insensitive Replacement

Use flags for case-insensitive matching:


text = "Hello HELLO hello"
new_text, count = re.subn(r'hello', 'hi', text, flags=re.IGNORECASE)
print(f"Modified text: {new_text}")
print(f"Number of replacements: {count}")


Modified text: hi hi hi
Number of replacements: 3

Conclusion

re.subn() is a powerful tool when you need to track the number of replacements made in a string. It combines the functionality of pattern replacement with count information.

It's particularly useful when you need to verify how many changes were made to a string, making it ideal for text processing and validation tasks.