Python String startswith() Method
The startswith() method checks if a string starts with the specified prefix. It returns True if the string starts with the specified prefix, and False otherwise.
Syntax
string.startswith(prefix, start, end)
Paremeters
prefix (required): The substring or tuple of substrings to check.
start (optional): Index to start checking from. Default is 0.
end (optional): Index to stop checking (exclusive). Default is length of the string.
Return Value
Returns True if the string starts with the specified prefix.
Returns False otherwise.
Examples
Check if a String Starts With a Specific Prefix
text = "Python is awesome"
print(text.startswith("Python")) # Output: True
print(text.startswith("awesome")) # Output: False
With start Parameter
If you only provide the start parameter, Python checks whether the substring from that index to the end of the string starts with the specified prefix.
text = "Python is awesome"
print(text.startswith("is", 7)) # Output: True
With start and end Parameters
If you provide both the start and end parameter, Python checks whether the substring from the start index up to (but not including) the end index begins with the specified prefix.
text = "Python is awesome"
print(text.startswith("is", 7, 9)) # Output: True
print(text.startswith("is", 7, 8)) # Output; False
The end parameter is exclusive meaning the suffix check doesn’t include the character at the end index.
Tuple of Prefixes
You can provide a tuple of prefixes if you want to check if a string starts with any one of multiple possible prefixes.
text = "Python is awesome"
print(text.startswith(("Java", "Python", "Kotlin"))) # True
Case-Sensitivity
The startswith() method is case-sensitive, meaning it treats uppercase and lowercase letters as distinct characters.
text = "Python is awesome"
print(text.startswith("Python")) # True
print(text.startswith("python")) # False
If you need to check if the string ends with the specified suffix, you can use the endswith() method.