String Prefix Check करना
Python में String Class में startswith(string) Method होता है। यह Method वह Prefix String Accept करता है जिसे आप Search करना चाहते हैं और String Object पर Call किया जाता है।
उदाहरण
>>> 'hello world'.startswith('hell')
True
>>> 'hello world'.startswith('nope')
False
Multiple Prefixes Check करना:
>>> 'hello world'.startswith(('he', 'ha', 'hi'))
True
>&>> 'hello world'.startswith(('bye', 'hi'))
False
Start/End Position के साथ:
>>> 'hello world'.startswith('world', 6)
True
>>> 'hello world'.startswith('hello', 0, 5)
True
Alternative: Regular Expression का उपयोग
re Module (Regular Expression) से re.search('^' + prefix, string) का उपयोग करके भी यह Find कर सकते हैं कि String Given Prefix से Start होता है या नहीं। Regex ^ को Line की Start के रूप में Interpret करता है।
>>> import re
>>> bool(re.search('^hell', 'hello world'))
True
>>> bool(re.search('^nope', 'hello world'))
False
Performance:
str.startswith()- Fastest, Built-in, No Regex Overheadre.search()- Flexible (Patterns), लेकिन Slower
Best Practice:
# Simple Prefix Check के लिए
if filename.startswith('error_'):
process_error_log(filename)
# Multiple Prefixes
if filename.startswith(('error_', 'warn_', 'debug_')):
process_log(filename)