Python string startswith() function returns True
if the string starts with the given prefix, otherwise it returns False
.
Table of Contents
Python String startswith()
This function syntax is:
str.startswith(prefix[, start[, end]])
The prefix can be a string or a tuple of string prefixes to look for in the string.
The start is an optional argument to specify the index from where test starts.
The end is an optional argument to specify the index where the test has to stop.
Python string starts with example
Let’s look at a simple example of python string startswith() function.
s = 'Python is Awesome'
# without start and end
print(s.startswith('Python'))
Let’s look at some examples with the start argument.
s = 'Python is Awesome'
print(s.startswith('Python', 3))
print(s.startswith('hon', 3))
Output:
False
True
Since the start index is 3, the test will use the sub-string “hon is Awesome”. That’s why the first output is False and the second one is True.
Let’s look at some examples with the start and end arguments.
s = 'Python is Awesome'
print(s.startswith('is', 7, 10))
print(s.startswith('Python is', 0, 10))
print(s.startswith('Python is', 0, 6))
Output:
True
True
False
For the first print statement, the substring is “is the ” i.e. starting with “is” and hence the output is True.
In the second print statement, the substring is “Python is A” and hence the output is True.
For the third print statement, the substring is “Python” that doesn’t start with “Python is”, hence the output is False.
Python string startswith() example with Tuple
Let’s look at some examples with Tuple of strings as the prefix.
s = 'Python is Awesome'
print(s.startswith(('is', 'Python')))
print(s.startswith(('is', 'hon'), 7))
Output:
True
True
For the first print statement, string starts with “Python” and hence the output is True.
For the second print statement, string test begins from index position 7. So the substring is “is Awesome” which starts with “is” and hence the output as True.
Reference: Official Documentation
Nice and detailed explanation,
Thanks for sharing,