re.subn() method in Python is used to search for a pattern in a string and replace it with a new substring. It not only performs the replacement but also tells us how many times the replacement was made. We can use this method when we need to replace patterns or regular expressions in text and get a count of how many changes were made. We can do this using the re.subn() method in the re module.
Let's understand this with the help of example:
Python
import re
# Original string
s = "Geeks for Geeks"
# Replace 'cats' with 'dogs'
new_s, count = re.subn("nerds", "geeks", s)
print(new_s)
print("Replacements made:", count)
OutputGeeks for Geeks
Replacements made: 0
Syntax of re.subn() in Python
The syntax for the re.subn() method is as follows:
re.subn(pattern, repl, string, count=0, flags=0)
Parameters:
- pattern: This is the regular expression or pattern that we want to search for in the string.
- repl: This is the replacement string or a function that will replace the matched pattern.
- string: This is the original string where the search and replacement will take place.
- count (optional): This is the maximum number of replacements to make. The default value is 0, which means "replace all occurrences."
- flags (optional): This is used to modify the behavior of the pattern matching, like re.IGNORECASE, re.MULTILINE, etc.
Return Value:
- The modified string with the replacements.
- The number of replacements made.
Using Regular Expressions with re.subn()
We can also use regular expressions to replace patterns that match more complex rules, not just fixed strings. This code uses a regular expression to find phone numbers in a specific format (xxx-xxx-xxxx) and replaces them with a placeholder XXX-XXX-XXXX. The code also prints how many replacements were made.
Python
import re
# Original string
s = "My phone number is 123-456-7890 and my friend's is 987-654-3210"
# Replace all phone numbers (pattern: digits followed by hyphens)
new_s, count = re.subn(r"\d{3}-\d{3}-\d{4}", "XXX-XXX-XXXX", s)
print(new_s)
print(count)
OutputMy phone number is XXX-XXX-XXXX and my friend's is XXX-XXX-XXXX
2
Case-Insensitive Replacement
If we want to replace words regardless of their case, we can use the re.IGNORECASE flag. This code uses a regular expression to find occurrences of the word "test", regardless of case.
Python
import re
# Original string
s = "This is a Test. This is another Test."
# Replace 'test' with 'exam', ignoring case
new_s, count = re.subn(r"test", "exam", s, flags=re.IGNORECASE)
print(new_s)
print("Replacements made:", count)
OutputThis is a exam. This is another exam.
Replacements made: 2
This example replaces all HTML tags with the placeholder [TAG] and counts how many tags were replaced. This code is useful for sanitizing or cleaning HTML tags.
Python
import re
text = "<div>Hello</div> <p>World</p>"
pattern = r"</?\w+>" # Match HTML tags
replacement = "[TAG]"
modified_text, count = re.subn(pattern, replacement, text)
print(modified_text)
print(count)
Output[TAG]Hello[TAG] [TAG]World[TAG]
4
Similar Reads
re.search() in Python re.search() method in Python helps to find patterns in strings. It scans through the entire string and returns the first match it finds. This method is part of Python's re-module, which allows us to work with regular expressions (regex) simply. Example:Pythonimport re s = "Hello, welcome to the worl
3 min read
re.sub() - Python RegEx re.sub() method in Python parts of a string that match a given regular expression pattern with a new substring. This method provides a powerful way to modify strings by replacing specific patterns, which is useful in many real-life tasks like text processing or data cleaning.Pythonimport re a = "app
2 min read
re.match() in Python re.match method in Python is used to check if a given pattern matches the beginning of a string. Itâs like searching for a word or pattern at the start of a sentence. For example, we can use re.match to check if a string starts with a certain word, number, or symbol. We can do pattern matching using
2 min read
Python - re.compile() In Python, re.compile() from the re module creates a regex object from a regular expression pattern. This object lets you perform operations like search(), match(), and findall(). In this article, we will understand about re.compile() method.Pythonimport re # Compile the pattern pattern = re.compile
2 min read
Reversing a List in Python In this article, we are going to explore multiple ways to reverse a list. Python provides several methods to reverse a list using built-in functions and manual approaches. The simplest way to reverse a list is by using the reverse() method. Let's take an example to reverse a list using reverse() met
4 min read