Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python re sub() method



The Pythonre.sub() method is used to substitute occurrences of a pattern in a string with another string. It searches for all non-overlapping matches of the pattern in the input string and replaces them with the specified replacement string.

This method is helpful for performing global search and replace operations on strings using regular expressions. It provides flexibility in pattern matching and replacement allowing for complex transformations of text data.

With optional parameters for count and flagsre.sub() method offers control over the number of replacements and the matching behavior by making it a versatile tool for text processing tasks in Python.

Syntax

Following is the syntax and parameters of Pythonre.sub() method −

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

Parameter

The Following are the parameters of the pythonre.sub() method −

  • pattern: The regular expression pattern to search for.
  • repl: The replacement string or a function to be called for each match.
  • string: The input string to perform the substitution on.
  • count(optional): Maximum number of substitutions to make. The default is 0 which means replace all occurrences.
  • flags(optional): Flags to modify the matching behavior (e.g., re.IGNORECASE)

Return value

This method returns an iterator of match objects

Example 1

Following is the basic example of pythonre.sub() method, in which all numeric sequences in the string are replaced with the string 'number' −

import reresult = re.sub(r'\d+', 'number', 'Welcome to Tutorialspoint learning 2024')print(result)

Output

Welcome to Tutorialspoint learning number

Example 2

This example uses capturing groups in both the pattern and the replacement string to rearrange a date format.

import reresult = re.sub(r'(\d+)-(\d+)-(\d+)', r'\3/\2/\1', 'Date: 2022-01-01')print(result)

Output

Date: 01/01/2022

Example 3

Here in this example a output of the function 'square' is used as the replacement. It squares each numeric match found in the string −

import redef square(match):    num = int(match.group())    return str(num ** 2)result = re.sub(r'\d+', square, 'Numbers: 1 2 3 4 5')print(result)

Output

Numbers: 1 4 9 16 25

Example 4

In this example the count=1 argument limits the number of substitutions to 1, so only the first numeric sequence is replaced −

import reresult = re.sub(r'\d+', 'number', 'There are 123 apples and 456 oranges.', count=1)print(result)

Output

There are number apples and 456 oranges.
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp