Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python program to extract numeric suffix from string
Next article icon

Python program to Extract Mesh matching Strings

Last Updated : 01 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a character mesh, containing missing characters, match the string which matches the mesh.

Example:

Input : test_list = [“geeks”, “best”, “peeks”], mesh = “_ee_s” 
Output : [‘geeks’, ‘peeks’] 
Explanation : Elements according to mesh are geeks and peeks.

Input : test_list = [“geeks”, “best”, “test”], mesh = “_e_t” 
Output : [‘best’, ‘test’] 
Explanation : Elements according to mesh are best and test. 

Method #1: Using loop + all() + len() + zip() 

The combination of the above can be used to solve this problem. In this, we perform the task of matching mesh and each string using zip() and all() is used to check for all strings, len() is used to test for correct string length matching mesh.

Python3




# Python3 code to demonstrate working of
# Extract Mesh matching Strings
# Using len() + loop + zip() + all()
 
# initializing list
test_list = ["geeks", "best", "peeks", "for", "seeks"]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing mesh
mesh = "_ee_s"
 
res = []
for sub in test_list:
     
    # testing for matching mesh, checking each character and length
    if (len(sub) == len(mesh)) and all((ele1 == "_") or (ele1 == ele2)
       for ele1, ele2 in zip(mesh, sub)):
        res.append(sub)
 
# printing result
print("The extracted strings : " + str(res))
 
 
Output
The original list : ['geeks', 'best', 'peeks', 'for', 'seeks'] The extracted strings : ['geeks', 'peeks', 'seeks']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2: Using list comprehension

This solves the problem in a similar way as the above method, the only difference here is that 1 liner solution is provided. 

Python3




# Python3 code to demonstrate working of
# Extract Mesh matching Strings
# Using list comprehension
 
# initializing list
test_list = ["geeks", "best", "peeks", "for", "seeks"]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing mesh
mesh = "_ee_s"
 
# one liner to solve this problem
res = [sub for sub in test_list if (len(sub) == len(mesh)) and all((ele1 == "_") or (ele1 == ele2)
      for ele1, ele2 in zip(mesh, sub))]
 
# printing result
print("The extracted strings : " + str(res))
 
 
Output
The original list : ['geeks', 'best', 'peeks', 'for', 'seeks'] The extracted strings : ['geeks', 'peeks', 'seeks']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 3: Using the filter() function along with lambda function

  • Start by initializing the list of strings test_list and the mesh string mesh.
  • Create an empty list result to store the strings that match the mesh.
  • Loop through each string s in test_list.
  • Check if the length of s is equal to the length of mesh. If not, move on to the next string.
  • Loop through each character c in s and its corresponding character m in mesh.
  • If m is equal to “_”, move on to the next character. Otherwise, check if c is equal to m. If not, move on to the next string.
  • If the loop completes without finding any mismatches, append the string s to the result list.
  • Once all strings have been checked, return the result list containing the matching strings.

Python3




# Python3 code to demonstrate working of
# Extract Mesh matching Strings
# Using filter() + lambda function
 
# initializing list
test_list = ["geeks", "best", "peeks", "for", "seeks"]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing mesh
mesh = "_ee_s"
 
# filtering the list using filter() and lambda function
res = list(filter(lambda x: len(x) == len(mesh) and all((ele1 == "_") or (ele1 == ele2) for ele1, ele2 in zip(mesh, x)), test_list))
 
# printing result
print("The extracted strings : " + str(res))
 
 
Output
The original list : ['geeks', 'best', 'peeks', 'for', 'seeks'] The extracted strings : ['geeks', 'peeks', 'seeks']

Time Complexity: O(n*m), where n is the number of strings in the input list, and m is the length of the mesh.
Auxiliary Space: O(k), where k is the number of strings that match the mesh.

Method #4: Using a for loop and a helper function

Python3




def match_mesh(mesh, string):
    """
    Helper function to check if a given string matches with the mesh.
    """
    if len(mesh) != len(string):
        return False
    for i in range(len(mesh)):
        if mesh[i] != '_' and mesh[i] != string[i]:
            return False
    return True
 
# initializing list
test_list = ["geeks", "best", "peeks", "for", "seeks"]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing mesh
mesh = "_ee_s"
 
# extracting strings matching the mesh using for loop and helper function
res = []
for string in test_list:
    if match_mesh(mesh, string):
        res.append(string)
 
# printing result
print("The extracted strings : " + str(res))
 
 
Output
The original list : ['geeks', 'best', 'peeks', 'for', 'seeks'] The extracted strings : ['geeks', 'peeks', 'seeks']

Time complexity: O(n * m), where n is the number of strings in the list and m is the length of the mesh.
Auxiliary space: O(k), where k is the number of strings that match the mesh.



Next Article
Python program to extract numeric suffix from string
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python program to extract numeric suffix from string
    Given a string of characters with digits embedded in it. The task is to write a Python program to extract all the numbers that are trailing, i.e at the suffix of the string. Examples: Input : test_str = "GFG04"Output : 04Explanation : 04 is suffix of string and number hence extracted. Input : test_s
    7 min read
  • Python program to extract Strings between HTML Tags
    Given a String and HTML tag, extract all the strings between the specified tag. Input : '<b>Gfg</b> is <b>Best</b>. I love <b>Reading CS</b> from it.' , tag = "br" Output : ['Gfg', 'Best', 'Reading CS']Explanation : All strings between "br" tag are extracted. Inpu
    5 min read
  • Python program to find String in a List
    Searching for a string in a list is a common operation in Python. Whether we're dealing with small lists or large datasets, knowing how to efficiently search for strings can save both time and effort. In this article, we’ll explore several methods to find a string in a list, starting from the most e
    3 min read
  • Python | Extract odd length words in String
    Sometimes, while working with Python, we can have a problem in which we need to extract certain length words from a string. This can be extraction of odd length words from the string. This can have application in many domains including day-day programming. Lets discuss certain ways in which this tas
    5 min read
  • Python - Extract Indices of substring matches
    Given a String List, and a substring, extract list of indices of Strings, in which that substring occurs. Input : test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Gfg is useful"], K = "Gfg" Output : [0, 2, 3] Explanation : "Gfg" is present in 0th, 2nd and 3rd element as substring. Input : tes
    5 min read
  • Python - Extract String till Numeric
    Given a string, extract all its content till first appearance of numeric character. Input : test_str = "geeksforgeeks7 is best" Output : geeksforgeeks Explanation : All characters before 7 are extracted. Input : test_str = "2geeksforgeeks7 is best" Output : "" Explanation : No character extracted as
    5 min read
  • Python program to find occurrence to each character in given string
    Given a string, the task is to write a program in Python that prints the number of occurrences of each character in a string. There are multiple ways in Python, we can do this task. Let's discuss a few of them. Method #1: Using set() + count() Iterate over the set converted string and get the count
    5 min read
  • Python Program To Check If A String Is Substring Of Another
    Given two strings s1 and s2, find if s1 is a substring of s2. If yes, return the index of the first occurrence, else return -1. Examples :  Input: s1 = "for", s2 = "geeksforgeeks" Output: 5 Explanation: String "for" is present as a substring of s2. Input: s1 = "practice", s2 = "geeksforgeeks" Output
    3 min read
  • Python - Extract indices of Present, Non Index matching Strings
    Given two strings, extract indices of all characters from string 1 which are present in the other string, but not in the same index. Input : test_str1 = 'pplg', test_str2 = 'pineapple' Output : [0, 1, 2] Explanation : ppl is found in 2nd string, also not on same index as 1st. Input : test_str1 = 'pi
    6 min read
  • Python program to extract characters in given range from a string list
    Given a Strings List, extract characters in index range spanning entire Strings list. Input : test_list = ["geeksforgeeks", "is", "best", "for", "geeks"], strt, end = 14, 20 Output : sbest Explanation : Once concatenated, 14 - 20 range is extracted.Input : test_list = ["geeksforgeeks", "is", "best",
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences