Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python program to find all close matches of input string from a list
In this tutorial, we will find all strings from a list that closely match a given input string. A close match means either the string starts with the input element or the input element starts with the string.
Problem Statement
Given a list of strings and an input element, find all strings that have a close match with the element ?
Input: strings = ["Lion", "Li", "Tiger", "Tig"] element = "Lion" Output: Lion Li
Algorithm
We can solve this using the startswith() method with the following steps ?
- Initialize the string list and input element
- Loop through each string in the list
- Check if the string starts with the element OR the element starts with the string
- If either condition is true, include it in the result
Example
# Initialize the string list and element
strings = ["Lion", "Li", "Tiger", "Tig"]
element = "Lion"
print("Close matches:")
for string in strings:
# Check if string starts with element or element starts with string
if string.startswith(element) or element.startswith(string):
print(string, end=" ")
print() # New line after results
Close matches: Lion Li
How It Works
The condition string.startswith(element) or element.startswith(string) checks two cases ?
- "Lion".startswith("Lion") ? True (exact match)
- "Li".startswith("Lion") ? False, but "Lion".startswith("Li") ? True
- "Tiger".startswith("Lion") ? False, and "Lion".startswith("Tiger") ? False
Alternative Approach Using List Comprehension
strings = ["Lion", "Li", "Tiger", "Tig"]
element = "Lion"
# Using list comprehension
close_matches = [s for s in strings if s.startswith(element) or element.startswith(s)]
print("Close matches:", " ".join(close_matches))
Close matches: Lion Li
Complete Function Implementation
def find_close_matches(strings, element):
"""Find all strings that closely match the given element"""
matches = []
for string in strings:
if string.startswith(element) or element.startswith(string):
matches.append(string)
return matches
# Test the function
strings = ["Lion", "Li", "Tiger", "Tig", "Python", "Py"]
element = "Lion"
result = find_close_matches(strings, element)
print(f"Close matches for '{element}': {result}")
# Test with different element
element2 = "Py"
result2 = find_close_matches(strings, element2)
print(f"Close matches for '{element2}': {result2}")
Close matches for 'Lion': ['Lion', 'Li'] Close matches for 'Py': ['Python', 'Py']
Conclusion
Use the startswith() method to find close matches by checking if strings start with each other. This approach works well for prefix-based matching and can be implemented using loops or list comprehension.
Advertisements
