Python re.subn() Method
re.subn() is a function in the Python re module used toReplace matches and return the replacement count.
It returns the same value as re.sub() Similar, but returns a tuple containing the resulting string and the total number of replacements.
Word meaning: subn is short for "substitute and return number".
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 (resulting string, number of replacements).
Example
Example 1: basic usage
Example
import
re
text
=
"Python Python Python"
Replace all
result
=
re
.
subn
(
r
'Python'
,
'Java'
,
text
)
(
"After replacement:"
,
result
[
0
]
)
(
"Number of replacements:"
,
result
[
1
]
)
Expected output:
替换后: Java Java Java
替换次数: 3
Example 2: limit 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
)
(
"After replacement:"
,
result
[
0
]
)
(
"Number of replacements:"
,
result
[
1
]
)
Expected output:
替换后: Java Java Python
替换次数: 2
Example 3: count occurrences of a sensitive word
Example
import
re
text
=
"This product is good, the product quality is nice, the product price is reasonable"
Replace the sensitive word and count the occurrences
result
=
re
.
subn
(
r
'Product'
,
'Item'
,
text
)
(
"After replacement:"
,
result
[
0
]
)
(
"Sensitive word occurrences:"
,
result
[
1
]
)
Expected output:
替换后: 这个商品很好,商品质量不错,商品价格合理
敏感词出现次数: 3
Python re Module