Test the starting and ending characters of a string

Download python eBook

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

Stats

Contributors: 5
2017-04-11
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook