The Wayback Machine - https://web.archive.org/web/20220709015104/https://www.geeksforgeeks.org/python-wildcard-substring-search/
Skip to content
Related Articles

Related Articles

Python – Wildcard Substring search

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 22 Apr, 2020

Sometimes, while working with Python Strings, we have problem in which, we need to search for substring, but have some of characters missing and we need to find the match. This can have application in many domains. Lets discuss certain ways in which this task can be performed.

Method #1 : Using re.search()
This is one of the way in which this task can be performed. In this, we feed the regex compile with the substring and search for it using main string in search().




# Python3 code to demonstrate working of 
# Wildcard Substring search
# Using re.search()
import re
      
# initializing string
test_str = 'geeksforgeeks is best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing Substring
sub_str = '..st'
  
# Wildcard Substring search
# Using re.search()
temp = re.compile(sub_str) 
res = temp.search(test_str)
  
# printing result 
print("The substring match is : " + str(res.group(0))) 

Output :

The original string is : geeksforgeeks is best for geeks                                                                
The substring match is : best     

 

Method #2 : Using re.finditer()
This is yet another way to solve this problem. In this, we can also extract the position of match if required.




# Python3 code to demonstrate working of 
# Wildcard Substring search
# Using re.finditer()
import re
      
# initializing string
test_str = 'geeksforgeeks is best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing Substring
sub_str = '..st'
  
# Wildcard Substring search
# Using re.finditer()
temp = re.compile(sub_str) 
res = temp.search(test_str)
  
# printing result 
print("The substring match is : " + str(res.group(0))) 

Output :

The original string is : geeksforgeeks is best for geeks                                                                
The substring match is : best     

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!