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 - Find dictionary keys present in a Strings List
Next article icon

Python – Find all close matches of input string from a list

Last Updated : 03 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, there are multiple ways to find all close matches of a given input string from a list of strings.

Using startswith()

startswith() function is used to identify close matches for the input string. It checks if either the strings in the list start with the input or if the input starts with them.

Python
s = ["Lion", "Li", "Tiger", "Tig"] a = "Lion"  # Iterate through each string in the list for string in s:     if string.startswith(a) or a.startswith(string):         print(string, end=" ") 

Output
Lion Li 

Explanation:

  • string.startswith(a): Checks if the current string from the list s starts with the string a.
  • a.startswith(string): Checks if the string a starts with the current string from the list s.

Let’s understand various other methods to Find all close matches of input string from a list.

Table of Content

  • Using String Slicing
  • Two-Pointer Technique (Sorted)
  • Using Regular Expressions

Using String Slicing

Substring comparison can be used to identify matches. By checking if one string is a prefix of another, close matches can be determined.

Python
s = ["Lion", "Li", "Tiger", "Tig"] a = "Lion"  #Iterate through each string in a list for string in s:     if string[:len(a)] == a or a[:len(string)] == string:         print(string, end=" ") 

Output
Lion Li 

Explanation:

  • string[:len(a)] == a: Extracts the first len(a) characters of string to check if string starts with a.

Two-Pointer Technique (Sorted)

If the list is sorted, you can use a two-pointer approach to check prefixes:

Python
s = ["Lion", "Li", "Tiger", "Tig"] a = "Lion"  #Sort the list of strings to process in order s.sort()   # Initialize two pointers: `i` starts at the beginning,    #`j` at the end of the list i, j = 0, len(s) - 1  #Initialize ana empty list result = []  #Use a while loop to iterate through the list  while i <= j:     if s[i].startswith(a) or a.startswith(s[i]):         result.append(s[i])     i += 1  print(" ".join(result)) 

Output
Li Lion 

Explanation:

  • s.sort(): Sorts the list lexicographically (alphabetical order).
  • s[i].startswith(a) or a.startswith(s[i]): Checks if the current string (s[i]) starts with the reference string a.

Using Regular Expressions

Regular expressions allow you to match patterns efficiently:

Python
import re  s = ["Lion", "Li", "Tiger", "Tig"] a = "Lion"  # Create a regex pattern that checks if a string starts with `a`  # or if it starts with any string in `s` regex = f"^{re.escape(a)}|^{re.escape('|'.join(s))}"  # - `re.escape(a)` escapes special characters in `a`  # (if any) to avoid regex errors. # - `re.escape('|'.join(s))` joins all strings in  matches = [string for string in s if re.match(regex, string) or re.match(regex, a)] print(" ".join(matches)) 

Output
Lion Li Tiger Tig 

Explanation :

  • ^{re.escape(‘|’.join(s))}: Matches strings starting with any string in s, combined using the | (OR) operator.
  • Filters the strings in s by checking if either the string itself or the reference string a matches the regex.


Next Article
Python - Find dictionary keys present in a Strings List

S

Shashank Mishra
Improve
Article Tags :
  • DSA
  • Python
  • Python string-programs
  • python-string
Practice Tags :
  • python

Similar Reads

  • Python | Group strings at particular element in list
    Sometimes, while working with Python list, we can have a problem in which we have to group strings in a way that at occurrence of particular element, the string list is grouped. This can be a potential problem of day-day programming. Let's discuss certain way in which this problem can be performed.
    7 min read
  • Remove all the occurrences of an element from a list in Python
    The task is to perform the operation of removing all the occurrences of a given item/element present in a list. Example Input1: 1 1 2 3 4 5 1 2 1 Output1: 2 3 4 5 2 Explanation : The input list is [1, 1, 2, 3, 4, 5, 1, 2] and the item to be removed is 1. After removing the item, the output list is [
    4 min read
  • How Can I Find All Matches to a Regular Expression in Python?
    In Python, regular expressions (regex) are a powerful tool for finding patterns in text. Whether we're searching through logs, extracting specific data from a document, or performing complex string manipulations, Python's re module makes working with regular expressions straightforward. In this arti
    3 min read
  • Python - Find dictionary keys present in a Strings List
    Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the extraction of dictionary keys from strings list feeded. This problem can have application in many domains including data. Lets discuss certain ways in which this task can be performed. Method #1: U
    7 min read
  • Convert string to a list in Python
    Our task is to Convert string to a list in Python. Whether we need to break a string into characters or words, there are multiple efficient methods to achieve this. In this article, we'll explore these conversion techniques with simple examples. The most common way to convert a string into a list is
    2 min read
  • Python - Convert list of string to list of list
    In Python, we often encounter scenarios where we might have a list of strings where each string represents a series of comma-separated values, and we want to break these strings into smaller, more manageable lists. In this article, we will explore multiple methods to achieve this. Using List Compreh
    3 min read
  • Find line number of a specific string or substring or word from a .txt file in Python
    Finding the line number of a specific string and its substring is a common operation performed by text editors or any application with some level of text processing capabilities.  In this article, you will learn how to find line number of a specific string or substring or word from a .txt (plain tex
    4 min read
  • Python - Filter list elements starting with given Prefix
    We are given a list we need to filter list elements that are starting with given prefix. For example, a = ['apple', 'banana', 'avocado', 'apricot', 'cherry'] and given prefix is p = 'ap' we need to filter all the list elements that are starting with given prefix so that output should be ['apple', 'a
    2 min read
  • Find all strings that match specific pattern in a dictionary
    Given a dictionary of words, find all strings that match the given pattern where every character in the pattern is uniquely mapped to a character in the dictionary. Examples: Input: dict = ["abb", "abc", "xyz", "xyy"]; pattern = "foo" Output: [xyy abb] xyy and abb have same character at index 1 and
    15+ min read
  • Python String endswith() Method
    The endswith() method is a tool in Python for checking if a string ends with a particular substring. It can handle simple checks, multiple possible endings and specific ranges within the string. This method helps us make our code cleaner and more efficient, whether we're checking for file extensions
    3 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