Python Language String Methods Test the starting and ending characters of a string

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

In order to test the beginning and ending of a given string in Python, one can use the methods str.startswith() and str.endswith().


str.startswith(prefix[, start[, end]])

As it's name implies, str.startswith is used to test whether a given string starts with the given characters in prefix.

>>> s = "This is a test string"
>>> s.startswith("T")
True
>>> s.startswith("Thi")
True
>>> s.startswith("thi")  
False

The optional arguments start and end specify the start and end points from which the testing will start and finish. In the following example, by specifying a start value of 2 our string will be searched from position 2 and afterwards:

>>> s.startswith("is", 2)
True

This yields True since s[2] == 'i' and s[3] == 's'.

You can also use a tuple to check if it starts with any of a set of strings

>>> s.startswith(('This', 'That'))
True
>>> s.startswith(('ab', 'bc'))
False

str.endswith(prefix[, start[, end]])

str.endswith is exactly similar to str.startswith with the only difference being that it searches for ending characters and not starting characters. For example, to test if a string ends in a full stop, one could write:

>>> s = "this ends in a full stop."
>>> s.endswith('.')
True
>>> s.endswith('!')
False

as with startswith more than one characters can used as the ending sequence:

>>> s.endswith('stop.')
True
>>> s.endswith('Stop.')
False

You can also use a tuple to check if it ends with any of a set of strings

>>> s.endswith(('.', 'something'))
True
>>> s.endswith(('ab', 'bc'))
False


Got any Python Language Question?