Javatpoint Logo
Javatpoint Logo

re.sub() function in python

The re.sub() is a function in the re (regular expression) module in Python. It is used to replace all occurrences of a pattern in a string with a new string.

The function takes three arguments:

  1. pattern: A regular expression pattern to be searched for in the input string.
  2. repl: The string to replace the occurrences of the pattern with.
  3. string: The input string in which to perform the search and replace.

The function returns a new string with all the occurrences of the pattern replaced with the new string.

Example:

Output:

Hello, Universe!

In this example, the function re.sub() replaces all occurrences of the string "World" with the string "Universe" in the input string "Hello, World!".

It can be useful for tasks such as removing specific characters, replacing specific words with synonyms, or converting the case of characters in a string.

Example:

Output:

1, 2, 3, 4, , 5, 6, , 7, 8, 9,

In this example, the function re.sub() replaces all occurrences of the string "0" with an empty string, effectively removing all occurrences of the digit 0 from the input string.

Additionally, re.sub() allows you to use capturing groups in the pattern argument to perform more sophisticated text substitution operations. A capturing group is a group of characters in a pattern that is matched as a single unit and can be referenced in the replacement string using the syntax \1, \2, etc.

Example:

Here's an example of using re.sub() to replace all occurrences of a specific pattern in a string and retain a portion of the original string in the replacement:

Output:

banana apple, date cherry

In this example, the function re.sub() replaces all occurrences of the pattern "(\w+), (\w+)" with the string "\\2 \\1", which is the result of swapping the two matched capturing groups. The capturing groups are specified using parentheses () in the pattern and are referenced using the syntax \1 and \2 in the replacement string.

Example:

An example of using re.sub() to convert all the characters in a string to uppercase:

Output:

HELLO WORLD!

In this example, the function re.sub() replaces all occurrences of the pattern "(\w)" with the uppercase version of the matched character. The capturing group (\w) is used to match individual characters in the input string, and the upper() method is used to convert each character to uppercase. The replacement "\\1".upper() combines the matched character with the uppercase conversion, resulting in an output string with all characters in uppercase.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA