Checking Prefixes and Suffixes (startswith, endswith)
π·οΈ Working with Strings In-Depth / Common String Methods
When working with text data, you often need to check whether a string begins or ends with a specific sequence of characters. Python provides two simple methods for this: startswith() and endswith(). These are incredibly useful when validating file extensions, checking URL protocols, or parsing log entries.
βοΈ What Are Prefix and Suffix Checks?
- A prefix is the beginning portion of a string. For example, in the string "hello_world.txt", the prefix "hello" appears at the start.
- A suffix is the ending portion of a string. In the same example, the suffix ".txt" appears at the end.
- The startswith() method checks if a string starts with a given prefix.
- The endswith() method checks if a string ends with a given suffix.
- Both methods return a boolean value: True if the condition is met, False otherwise.
π οΈ Using startswith()
- The basic syntax is: string.startswith(prefix)
- It returns True if the string begins with the specified prefix.
- Example: "report_final.pdf".startswith("report") returns True
- Example: "data_2024.csv".startswith("log") returns False
- You can also specify a starting position: string.startswith(prefix, start)
- Example: "error_log.txt".startswith("log", 6) returns True (starts checking from index 6)
π οΈ Using endswith()
- The basic syntax is: string.endswith(suffix)
- It returns True if the string ends with the specified suffix.
- Example: "image.png".endswith(".png") returns True
- Example: "document.pdf".endswith(".docx") returns False
- You can also check within a range: string.endswith(suffix, start, end)
- Example: "backup_2024_old.zip".endswith("old", 0, 14) returns True (only checks characters from index 0 to 13)
π Checking Multiple Options
Both methods accept a tuple of prefixes or suffixes to check against:
- startswith() with a tuple: string.startswith(("http", "https", "ftp")) returns True if the string starts with any of those protocols
- endswith() with a tuple: filename.endswith((".jpg", ".png", ".gif")) returns True if the file has any of those image extensions
- This is much cleaner than writing multiple or conditions
π΅οΈ Practical Examples
| Scenario | Code Example | Result |
|---|---|---|
| Check if URL uses HTTPS | url.startswith("https") | True for "https://example.com" |
| Validate file extension | file.endswith(".log") | True for "server.log" |
| Check multiple protocols | url.startswith(("http", "https")) | True for both HTTP and HTTPS URLs |
| Filter image files | name.endswith((".jpg", ".jpeg", ".png")) | True for "photo.jpg" or "icon.png" |
| Parse log severity | line.startswith("ERROR") | True for "ERROR: Connection timeout" |
β‘ Common Use Cases
- File processing: Check file extensions before reading or writing files
- URL validation: Verify that a URL uses the expected protocol
- Log parsing: Identify log entries by their starting keywords (INFO, WARNING, ERROR)
- Data cleaning: Remove or process strings that begin or end with specific characters
- Configuration checks: Validate that configuration keys follow naming conventions
π§ Key Takeaways
- startswith() and endswith() are case-sensitive by default
- Both methods accept a tuple for checking multiple prefixes or suffixes at once
- You can specify start and end indices to limit the search range
- These methods return True or False, making them perfect for conditional statements
- They are efficient and readable alternatives to using slicing or regular expressions for simple prefix/suffix checks
The startswith() and endswith() methods check whether a string begins or ends with a specified substring, returning True or False.
π§ Example 1: Basic prefix check with startswith()
Check if a simple word starts with a given letter.
text = "engineer"
result = text.startswith("eng")
print(result)
π€ Output: True
π§ Example 2: Basic suffix check with endswith()
Check if a filename ends with a specific file extension.
filename = "report.pdf"
result = filename.endswith(".pdf")
print(result)
π€ Output: True
π§ Example 3: Case sensitivity matters
Both methods are case-sensitive β uppercase and lowercase are treated as different.
text = "Python"
result_start = text.startswith("python")
result_end = text.endswith("ON")
print(result_start)
print(result_end)
π€ Output: False
π€ Output: False
π§ Example 4: Checking multiple possible prefixes at once
Pass a tuple of strings to check if the string starts with any of them.
url = "https://docs.python.org"
result = url.startswith(("http://", "https://"))
print(result)
π€ Output: True
π§ Example 5: Practical use β validating log file names
Engineers often need to verify file naming conventions before processing.
log_file = "error_2024_01_15.log"
starts_correctly = log_file.startswith("error_")
ends_correctly = log_file.endswith(".log")
print(starts_correctly)
print(ends_correctly)
π€ Output: True
π€ Output: True
π Comparison Table: startswith() vs endswith()
| Method | Checks | Returns True when string⦠|
Common use case |
|---|---|---|---|
startswith() |
Beginning of string | Starts with given substring | Validating prefixes (URLs, codes) |
endswith() |
End of string | Ends with given substring | Validating file extensions, suffixes |
When working with text data, you often need to check whether a string begins or ends with a specific sequence of characters. Python provides two simple methods for this: startswith() and endswith(). These are incredibly useful when validating file extensions, checking URL protocols, or parsing log entries.
βοΈ What Are Prefix and Suffix Checks?
- A prefix is the beginning portion of a string. For example, in the string "hello_world.txt", the prefix "hello" appears at the start.
- A suffix is the ending portion of a string. In the same example, the suffix ".txt" appears at the end.
- The startswith() method checks if a string starts with a given prefix.
- The endswith() method checks if a string ends with a given suffix.
- Both methods return a boolean value: True if the condition is met, False otherwise.
π οΈ Using startswith()
- The basic syntax is: string.startswith(prefix)
- It returns True if the string begins with the specified prefix.
- Example: "report_final.pdf".startswith("report") returns True
- Example: "data_2024.csv".startswith("log") returns False
- You can also specify a starting position: string.startswith(prefix, start)
- Example: "error_log.txt".startswith("log", 6) returns True (starts checking from index 6)
π οΈ Using endswith()
- The basic syntax is: string.endswith(suffix)
- It returns True if the string ends with the specified suffix.
- Example: "image.png".endswith(".png") returns True
- Example: "document.pdf".endswith(".docx") returns False
- You can also check within a range: string.endswith(suffix, start, end)
- Example: "backup_2024_old.zip".endswith("old", 0, 14) returns True (only checks characters from index 0 to 13)
π Checking Multiple Options
Both methods accept a tuple of prefixes or suffixes to check against:
- startswith() with a tuple: string.startswith(("http", "https", "ftp")) returns True if the string starts with any of those protocols
- endswith() with a tuple: filename.endswith((".jpg", ".png", ".gif")) returns True if the file has any of those image extensions
- This is much cleaner than writing multiple or conditions
π΅οΈ Practical Examples
| Scenario | Code Example | Result |
|---|---|---|
| Check if URL uses HTTPS | url.startswith("https") | True for "https://example.com" |
| Validate file extension | file.endswith(".log") | True for "server.log" |
| Check multiple protocols | url.startswith(("http", "https")) | True for both HTTP and HTTPS URLs |
| Filter image files | name.endswith((".jpg", ".jpeg", ".png")) | True for "photo.jpg" or "icon.png" |
| Parse log severity | line.startswith("ERROR") | True for "ERROR: Connection timeout" |
β‘ Common Use Cases
- File processing: Check file extensions before reading or writing files
- URL validation: Verify that a URL uses the expected protocol
- Log parsing: Identify log entries by their starting keywords (INFO, WARNING, ERROR)
- Data cleaning: Remove or process strings that begin or end with specific characters
- Configuration checks: Validate that configuration keys follow naming conventions
π§ Key Takeaways
- startswith() and endswith() are case-sensitive by default
- Both methods accept a tuple for checking multiple prefixes or suffixes at once
- You can specify start and end indices to limit the search range
- These methods return True or False, making them perfect for conditional statements
- They are efficient and readable alternatives to using slicing or regular expressions for simple prefix/suffix checks
Interactive Views
You are currently in π All-in-One mode. Use the tabs at the top to switch to π Theory Only or π» Code Only views.
The startswith() and endswith() methods check whether a string begins or ends with a specified substring, returning True or False.
π§ Example 1: Basic prefix check with startswith()
Check if a simple word starts with a given letter.
text = "engineer"
result = text.startswith("eng")
print(result)
π€ Output: True
π§ Example 2: Basic suffix check with endswith()
Check if a filename ends with a specific file extension.
filename = "report.pdf"
result = filename.endswith(".pdf")
print(result)
π€ Output: True
π§ Example 3: Case sensitivity matters
Both methods are case-sensitive β uppercase and lowercase are treated as different.
text = "Python"
result_start = text.startswith("python")
result_end = text.endswith("ON")
print(result_start)
print(result_end)
π€ Output: False
π€ Output: False
π§ Example 4: Checking multiple possible prefixes at once
Pass a tuple of strings to check if the string starts with any of them.
url = "https://docs.python.org"
result = url.startswith(("http://", "https://"))
print(result)
π€ Output: True
π§ Example 5: Practical use β validating log file names
Engineers often need to verify file naming conventions before processing.
log_file = "error_2024_01_15.log"
starts_correctly = log_file.startswith("error_")
ends_correctly = log_file.endswith(".log")
print(starts_correctly)
print(ends_correctly)
π€ Output: True
π€ Output: True
π Comparison Table: startswith() vs endswith()
| Method | Checks | Returns True when string⦠|
Common use case |
|---|---|---|---|
startswith() |
Beginning of string | Starts with given substring | Validating prefixes (URLs, codes) |
endswith() |
End of string | Ends with given substring | Validating file extensions, suffixes |