Test the starting and ending characters of a string

suggest change

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


String Methods:
* Test the starting and ending characters of a string

Table Of Contents
2 Filter
3 List
7 Loops
17 String Methods
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve