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:
The function returns a new string with all the occurrences of the pattern replaced with the new string.
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.
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.
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:
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.
An example of using re.sub() to convert all the characters in a string to uppercase:
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.
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week