Python tip 1: tuple argument for startswith/endswith methods
You'd probably know about the startswith()
and endswith()
string methods.
>>> sentence = 'This is a sample string'
>>> sentence.startswith('This')
True
>>> sentence.startswith('is')
False
>>> sentence.endswith('ing')
True
>>> sentence.endswith('ly')
False
But did you know that you can also pass a tuple
of strings?
>>> words = ['refuse', 'impossible', 'fire', 'present', 'read', 'shim']
>>> prefix = ('im', 're', 'use')
>>> [w for w in words if w.startswith(prefix)]
['refuse', 'impossible', 'read']
>>> [w for w in words if w.endswith(prefix)]
['refuse', 'fire', 'shim']
Video demo:
See also my 100 Page Python Intro ebook.