Python - String startswith()
startswith() method in Python checks whether a given string starts with a specific prefix. It helps in efficiently verifying whether a string begins with a certain substring, which can be useful in various scenarios like:
- Filtering data
- Validating input
- Simple pattern matching
Let’s understand by taking a simple example:
s = "GeeksforGeeks"
res = s.startswith("for")
print(res)
Output
False
Explanation: startswith() method checks if the string s starts with "for", and since it starts with "Geeks" instead of for, the result is False.
Syntax
string.startswith(prefix[, start[, end]])
Parameters:
- prefix: A string or a tuple of strings to check at the start.
- start (optional): Index to start checking from.
- end (optional): Index to stop checking.
Return Type: The method returns a Boolean:
- True if the string starts with the specified prefix.
- False if it does not.
Examples of startswith() method
Example 1: Basic Prefix Check
Here’s a simple example where we check if a given string starts with the word "for".
s = "GeeksforGeeks"
res = s.startswith("for")
print(res)
Output
False
Explanation: The string starts with "Geeks", so it returns True.
Example 2: Using start Parameter
Let’s check the string using the start parameter to begin from a specific index.
s = "GeeksforGeeks"
print(s.startswith("for", 5))
Output
True
Explanation: We're checking from index 5, and "for" starts from there hence the result is True.
Example 3: Using start and end Parameters
We can also check for stings within a given slice using star and end parameters.
s = "GeeksforGeeks"
print(s.startswith("for", 5, 8))
Output
True
Explanation: checking only between index 5 and 8 (non inclusive) and "for" lies in that slice, so it returns True.
Example 4: Checking Multiple Prefixes
We can also check if the string starts with any one of several prefixes by passing a tuple of prefixes.
s = "GeeksforGeeks"
res = s.startswith(("Geeks", "G"))
print(res)
Output
True
Explanation:
- We pass a tuple with two prefixes: "Geeks" and "G".
- The string starts with "Geeks", which is one of the options in the tuple, so the result is True.