Python re.subn() Method
re.subn()is the Pythonrere module function used toreplace matches and return the number of replacements.
It isre.sub()similar, but returns a tuple containing the replaced string and the total number of replacements.
Word Meaning: subnis the abbreviation for substitute and return number (replace and return the count).
Basic Syntax and Parameters
Syntax Format
re.subn(pattern, repl, string, count=0, flags=0)
Parameter Description
- pattern: The regular expression to match
- repl: The replacement text
- string: The original string
- count: The maximum number of replacements
- flags: Regular expression flags
Function Description
- Return Value: Returns a tuple (the replaced string, the number of replacements).
Examples
Example 1: Basic Usage
Example
import re
text = "Python Python Python"
# Replace all
result = re.subn(r'Python', 'Java', text)
print("After replacement:", result[0])
print("Replacement count:", result[1])
text = "Python Python Python"
# Replace all
result = re.subn(r'Python', 'Java', text)
print("After replacement:", result[0])
print("Replacement count:", result[1])
Expected output:
替换后: Java Java Java 替换次数: 3
Example 2: Limiting the Number of Replacements
<h2 class="example">Example
import re
text = "Python Python Python"
# Replace only 2 times
result = re.subn(r'Python', 'Java', text, count=2)
print("After replacement:", result[0])
print("Replacement count:", result[1])
text = "Python Python Python"
# Replace only 2 times
result = re.subn(r'Python', 'Java', text, count=2)
print("After replacement:", result[0])
print("Replacement count:", result[1])
Expected output:
替换后: Java Java Python 替换次数: 2
Example 3: Counting Sensitive Word Occurrences
Example
import re
text = "This product is good, the product quality is good, and the product price is reasonable."
# Replace sensitive words and count occurrences
result = re.subn(r'product', 'goods', text)
print("After replacement:", result[0])
print("Sensitive word occurrence count:", result[1])
text = "This product is good, the product quality is good, and the product price is reasonable."
# Replace sensitive words and count occurrences
result = re.subn(r'product', 'goods', text)
print("After replacement:", result[0])
print("Sensitive word occurrence count:", result[1])
Expected output:
替换后: 这个商品很好,商品质量不错,商品价格合理 敏感词出现次数: 3
Other Extensions
Python re Module