Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python re.subn() Method

Python re.subn() Method

Python re Module Python re Module


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

Function description


Example

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

(

"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

)

print

(

"After replacement:"

,

result

[

0

]

)

print

(

"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

)

print

(

"After replacement:"

,

result

[

0

]

)

print

(

"Sensitive word occurrences:"

,

result

[

1

]

)

Expected output:

替换后: 这个商品很好,商品质量不错,商品价格合理
敏感词出现次数: 3

Python re Module Python re Module