Python – startswith() and endswith() functions
Python provides built-in methods like startswith() and endswith() that are used to check if a string starts or ends with a specific substring. These functions help in string manipulation and validation tasks.
Let’s understand with an example:
s = "GeeksforGeeks"
# startswith()
# Check if `s` starts with "Geeks"
print(s.startswith("Geeks"))
# Check if "Geeks" is at position 4 to 10 in `s`
print(s.startswith("Geeks", 4, 10))
# endswith()
# Check if `s` ends with "Geeks"
print(s.endswith("Geeks"))
# Check if "Geeks" is at position 2 to 8 in `s`
print(s.endswith("Geeks", 2, 8))
Output
True False True False
Let’s understand some practical usecase of this startwith() and endwith() functions .
User Input Validation
We can use startswith() and endswith() to check if something the user types starts or ends with specific letters or words. This helps make sure the input is correct, like checking if an email address has the right beginning or ending.
# Define string variable 'a'
a = "user@123.com"
# Check if 'a' starts with "user" and ends with "@123.com"
if a.startswith("user") and a.endswith("@123.com"):
print("Valid")
Output
Valid
Log file parsing
We use startswith() and endswith() for log file parsing to check if a log entry starts with a specific timestamp or ends with a certain status. These functions help efficiently filter and analyze log entries based on patterns.
# Define the log entry string
s = "2024-12-29 12:00:00 - INFO - Completed"
# Check if `s` starts with today's date
if s.startswith("2024-12-29"):
print("Valid")
# Check if `s` ends with "Completed"
if s.endswith("Completed"):
print("Completed")
Output
Valid Completed
Filtering data
We can filter a list of strings by checking if each item starts or ends with specific substrings usingstartswith()and endswith(). This allows efficient selection of items that match desired patterns.
a = ["apple", "banana", "grape", "avocado"]
# filter items that start with "a" and end with "o"
res = [i for i in a if i.startswith("a") and i.endswith("o")]
print(res)
Output
['avocado']


