Python String startswith() Method
The Python startswith() method is used to check if a string starts with the specified substring, returning True if it does, False otherwise, and within the specified range if the arguments beg and end specify values.
Python String startswith() Syntax
Syntax of the startswith() method.
str.startswith(substr, beg=0,end=len(string));
Python String startswith() Parameters
- str – The string to be tested.
- substr – the specified substring.
- strbeg – optional parameter to set the start position of the string detection.
- strend – optional parameter to set the end position of the string to be detected.
Python String startswith() Return Value
Returns True if a string is detected, otherwise False.
Python String startswith() Example#1
The following example shows the use of the startswith() function, where we will check if the string starts with api
, then it will return True, otherwise it will return false.
var = "api for demos"
print(var.startswith("api"))
print(var.startswith("demos"))
Output:
Python String startswith() Example#2
Python string startswith() method with strbeg and strend arguments.
If we supply the strbeg and strend arguments, then startswith() will check if the substrings within starts and ends match the given substring.
text = "api for demos"
result = text.startswith('for demos', 3)
print(result)
result = text.startswith('for', 6, 9)
print(result)
Output:
Python String startswith() Example#3
Use the Python String startswith() method to check if the string starts with one of many items.
We can also pass a tuple to the Python String startswith() method instead of a string to match. In this case, the startswith() method will return True if the string starts with any of the items in the tuple.
string = "apidemos"
res = string.startswith(('api', 'apis', 'API', 'Demos'))
print(res)
string = "apple you."
res = string.startswith(('a', 'e', 'i', 'o', 'u'))
print(res)
string = "mango you."
res = string.startswith(('a', 'e', 'i', 'o', 'u'))
print(res)
Output: