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
How to match text at the start or end of a string in Python?
Checking if a string starts or ends with specific text patterns is a common task in Python programming. The startswith() and endswith() methods provide elegant solutions for pattern matching at string boundaries.
Using startswith() Method
The startswith() method returns True if the string begins with the specified prefix ?
Example
text = "Is USA colder than Australia?"
print(f"Starts with 'Is': {text.startswith('Is')}")
Starts with 'Is': True
Example
filename = "Hello_world.txt"
print(f"Starts with 'Hello': {filename.startswith('Hello')}")
Starts with 'Hello': True
Example
site_url = 'https://www.something.com'
print(f"Starts with 'http:': {site_url.startswith('http:')}")
print(f"Starts with 'https:': {site_url.startswith('https:')}")
Starts with 'http:': False Starts with 'https:': True
Using endswith() Method
The endswith() method returns True if the string ends with the specified suffix ?
Example
text = "Is USA colder than Australia?"
print(f"Ends with '?': {text.endswith('?')}")
Ends with '?': True
Example
filename = "Hello_world.txt"
print(f"Ends with '.txt': {filename.endswith('.txt')}")
Ends with '.txt': True
Checking Multiple Patterns with Tuples
Both methods accept tuples to check multiple patterns simultaneously. This is especially useful for file extension validation ?
Example
import os
filenames = ['file1.csv', 'document.txt', 'image.png', 'data.csv']
# Check if any files have .csv or .txt extensions
has_target_files = any(name.endswith(('.csv', '.txt')) for name in filenames)
print(f"Has CSV or TXT files: {has_target_files}")
# Get all files with specific extensions
target_files = [name for name in filenames if name.endswith(('.csv', '.txt'))]
print(f"Target files: {target_files}")
Has CSV or TXT files: True Target files: ['file1.csv', 'document.txt', 'data.csv']
Converting Lists to Tuples
The methods only accept tuples, not lists. If you have a list of patterns, convert it to a tuple ?
Example
# List of patterns (will cause error)
patterns = ['.csv', '.txt']
filenames = ['file1.csv', 'document.txt', 'image.png']
# Convert list to tuple for proper usage
target_files = [name for name in filenames if name.endswith(tuple(patterns))]
print(f"Files matching patterns: {target_files}")
Files matching patterns: ['file1.csv', 'document.txt']
Practical Usage in Conditionals
These methods work well with conditional statements and data processing ?
Example
filenames = ['data.csv', 'report.pdf', 'notes.txt']
extensions = ('.csv', '.txt')
if any(name.endswith(extensions) for name in filenames):
print("Found text-based files for processing")
processable_files = [name for name in filenames if name.endswith(extensions)]
print(f"Processable files: {processable_files}")
Found text-based files for processing Processable files: ['data.csv', 'notes.txt']
Conclusion
Use startswith() and endswith() for efficient string pattern matching. Pass tuples for multiple pattern checks and convert lists to tuples when needed. These methods integrate seamlessly with conditional logic and data filtering operations.
