[Tutor] startswith()/endswith() string methods
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Sat Jan 4 22:08:01 2003
On Sun, 5 Jan 2003, Lee Harr wrote:
> >x = ['ben','sandy','roger','hillary','john','betty']
>
> >How to get indexes of all names which begin with "b"
>
> How about a list comprehension?
>
> x = ['ben','sandy','roger','hillary','john','betty']
> [name for name in x if name.find('b') == 0]
> [name for name in x if name.find('er') >= 0]
Hi Lee,
By the way, strings support a 'startswith()' method, so we can replace an
expression like:
name.find('b') == 0
with
name.startswith('b')
They're equivalent, but using startswith() makes the intention of the code
slightly clearer to a human reader.
###
>>> names = ['ben','sandy','roger','hillary','john','betty']
>>> [i for i in range(len(names)) if names[i].startswith('b')]
[0, 5]
###
If we're curious, we can browse through a complete list of string methods
in the Library Documentation here:
http://www.python.org/doc/lib/string-methods.html
Hope this helps!