Welcome to Day 37 of the #80DaysOfChallenges journey! This beginner challenge involves filtering a list of image names to find those containing a search term, ignoring case, using string methods for normalization and containment checks to keep the original order. It's a straightforward way to practice list iteration, lowercasing for comparisons, and building results, common in search features or file management. If you're honing basics in string handling or list filtering without lambdas, this "Python image search" example illustrates a function that's simple to implement and adjust for other matching criteria like extensions or prefixes.
💡 Key Takeaways from Day 37: Image Search Function
This task creates a function that scans a list, checks for term matches case-insensitively, and collects hits in order. It's a basic filter pattern: normalize, loop check, append if true. We'll cover the essentials: function with term lowering, loop with containment, and example output preservation.
1. Function Design: Term Normalization
The image_search function takes images and term, returns a new list of matches:
def image_search(images, term):
term = term.lower() # normalize search term
Lowering term once preps for checks. The function builds a fresh list, leaving originals intact, ideal for non-destructive ops in apps like galleries.
2. Loop and Check: Case-Insensitive Matching
Build the result:
result = []
for img in images:
if term in img.lower(): # case-insensitive containment check
result.append(img)
return result
The loop iterates, lowers img for check, appends if term found. 'in' handles substrings efficiently. Keeps order, no sorting needed.
3. Example Usage: Testing with List
Demo it:
images = ["Sunset.png", "ocean_view.jpg", "CityNight.PNG", "sunrise-photo.jpeg"]
print(image_search(images, "sun")) # -> ['Sunset.png', 'sunrise-photo.jpeg']
For "sun", matches "Sunset.png" (sun) and "sunrise-photo.jpeg" (sun), ignoring case. Handles empties or no matches as [].
🎯 Summary and Reflections
This image search reinforces string basics in filtering, showing lower for case-insensitivity. It highlighted for me:
- Normalization key: One lower on term, per-item on img, balances efficiency.
- Containment simplicity: 'in' for substrings, easy yet powerful.
- Order preservation: Append in loop keeps input sequence.
Valued its real-use feel, like file searches. For more, add wildcards or regex.
Advanced Alternatives: List comp: [img for img in images if term.lower() in img.lower()], or fnmatch for patterns. Your filter tip? Comment!
🚀 Next Steps and Resources
Day 37 built search skills, ready for text tasks. In #80DaysOfChallenges? Added extensions? Share!
- Source Code for Challenge #37: scripts/image_search.py
- Main Repository: 80-days-of-challenges
- Daily Updates: Twitter/X (@Shahrouzlogs)
Top comments (0)