Extract all words that begin with x

Tycho Andersen tycho at tycho.ws
Tue May 11 00:17:30 EDT 2010


On Mon, May 10, 2010 at 10:23 PM, Terry Reedy <tjreedy at udel.edu> wrote:
> On 5/10/2010 5:35 AM, James Mills wrote:
>>
>> On Mon, May 10, 2010 at 6:50 PM, Xavier Ho<contact at xavierho.com>  wrote:
>>>
>>> Have I missed something, or wouldn't this work just as well:
>>>
>>>>>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas']
>>>>>> [word for word in list_of_strings if word[0] == 'a']
>>>
>>> ['awes', 'asdgas']
>>
>> I would do this for completeness (just in case):
>>
>>>>>> [word for word in list_of_strings if word and word[0] == 'a']
>>
>> Just guards against empty strings which may or may not be in the list.
>
>  ... word[0:1] does the same thing. All Python programmers should learn to
> use slicing to extract a  char from a string that might be empty.
> The method call of .startswith() will be slower, I am sure.

Why? Isn't slicing just sugar for a method call?

\t



More information about the Python-list mailing list