String startswith() and endswith()

Python StringViews 1928

String startswith() and endswith():

Python provides the built-in methods startswith() and endswith() for string manipulation. The startswith() and endswith() methods check if the string starts or ends with the given substring. You can also specify where your search should begin on a string.


The startswith() method checks if the string starts with the given substring or prefix. It returns True if the string starts with a given prefix else False.

The syntax is

string.startswith(prefix,start index, end index)

prefix: The substring needs to be checked for, in the given string.

start index: Starting from the start index, it checks for the prefix within the string.

end index:  It checks for the prefix in the string till the end index.

If the start index and the end index are not given, then by default 0 will be considered as the start index and -1 will be considered as end index. That means the whole string will be searched for the prefix.


>>> string_variable='Testing for starts with method'

# start index and end index are not given
>>> string_variable.startswith('testing')
>>> string_variable.startswith('Testing')

#start index is given
>>> string_variable.startswith('Testing',1)
>>> string_variable.startswith('starts',12)

#end index is given
>>> string_variable.startswith('starts',12,18)

When the start index and end index are given, the original string will be sliced as per the indexes and the prefix will be searched for, in the sliced string. That is why in the above example when the prefix  ‘Testing’ is searched in the string_variable, starting from position 1, False is returned.


The endswith() method checks if the string ends with the given substring or suffix. It returns True if the string ends with a given suffix, else False.

The syntax is similar to startswith(), except that it checks for the suffix of the string.


>>> string_variable='Testing for ends with method'

# start and end index not given
>>> string_variable.endswith('method')

# start index is given 
>>> string_variable.endswith('method',7)

# end index is given
>>> string_variable.endswith('method',7,-1)
>>> string_variable.endswith('method',7,len(string_variable))


Translate »