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

Python re.sub() Method

Python re.sub() Method

Python re Module Python re Module


re.sub() is a function in the Python re module used toReplace matches.

It finds all matching substrings in a string and replaces them with the specified content.

Word meaning: sub is short for "substitute".


Basic syntax and parameters

Syntax format


re.sub(pattern, repl, string, count=0, flags=0)

Parameter Description

Function description


Example

Example 1: basic replacement

Example

import

re

text

=

"Python is good, Python is great"

Replace Python with Java

result

=

re

.

sub

(

r

'Python'

,

'Java'

,

text

)

print

(

result

)

Expected output:

Java is good, Java is great

Example 2: replace a specified number of times

Example

import

re

text

=

"Python is good, Python is great"

Replace only the first one

result

=

re

.

sub

(

r

'Python'

,

'Java'

,

text

,

count

=

1

)

print

(

result

)

Expected output:

Java is good, Python is great

Example 3: replacement with a regular expression

Example

import

re

text

=

"My phone number is 138-1234-5678"

Replace the middle 4 digits of the phone number with ****

result

=

re

.

sub

(

r

'\d{4}'

,

'****'

,

text

)

print

(

result

)

Expected output:

我的手机号是 138-****-5678

Example 4: use group references

Example

import

re

text

=

"2024-04-02"

Swap the order of year, month and day

result

=

re

.

sub

(

r

'(\d{4})-(\d{2})-(\d{2})'

,

r

'\3/\2/\1'

,

text

)

print

(

result

)

Expected output:

02/04/2024

Example 5: use a function as the replacement

Example

import

re

text

=

"3 apples, 5 bananas, 8 oranges"

Replace each number with the number + 1

def

add_one

(

match

)

:

   

return

str

(

int

(

match.

group

(

)

)

1

)

result

=

re

.

sub

(

r

'\d+'

,

add_one

,

text

)

print

(

result

)

Expected output:

苹果4个,香蕉6个,橙子9个

Python re Module Python re Module