String startswith() and endswith()


Python StringViews 2303

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.

startswith():

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.

Example:

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

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

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

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

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.

endswith():

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.

Example:

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

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

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

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

 

Translate »