Check if string ends with one of the strings from a list
Check whether a string concludes with a given choice of substrings using str.endswith()
, which is capable of accepting a tuple:
This efficiently juxtaposes the file_name
with a tuple of choices
, confirming it as a valid document format.
Expanded answer
Case-insensitive check
For a case-insensitive check:
By invoking lower()
on file_name
, we ensure the matching operation remains case insensitive.
Regular expressions for intricate patterns
If you've got some fancy footwork in your patterns, regex is your go-to dance partner:
The re.IGNORECASE
option enables case-insensitive searches. Regex handles more convoluted patterns like a champ.
Code performance with timeit
Is your code more Usain Bolt or more tortoise? Use timeit
to measure performance:
Opt for the most effective method, balancing performance and code readability.
Optimization for multiple checks
If you've got a bunch of strings to check - no, we're not at a puppet show - you can optimize:
The filter
function paired with a lambda gives us a list of matching string endings faster than you can say "Expecto Patronum!".
Beyond the basics
Splitting file name and extension
Separating the file name and extension can be efficiently done using os.path.splitext
:
This method ensures accurate extraction of extensions - like a pro!
Pythonic code applications
Pythonic code is all about clean and concise expressions. Swap the old for loop with:
Swapping for loops with list comprehension keeps the syntax neat and tidy, and your code reviewers happy.
Was this article helpful?