Getting a unknown word out of a list with no spaces

Fredrik Lundh fredrik at
Thu Jul 17 11:41:41 CEST 2008

Alexnb wrote:

>>>>> "hello"[0]
>> 'h'
>>>>> "hello"[0] == "<"
>> False
>>>>> "hello"[0] == "h"
>> True
>>>>> "hello".startswith("h")
>> True

> really? That's just like C. I thought that it would fail because of the way
> lists work. Thanks!

what way?

the first three will fail if the string is empty.

     >>> ""[0]
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     IndexError: string index out of range

if you may end up doing this on an empty string, use slicing instead:

     >>> "hello"[:1] == "<"
     >>> ""[:1] == "<"

(startswith is perhaps more convenient, but method calls are rather 
expensive in Python, so if you're in a hurry, it's often better to use 
operators.  when in doubt, benchmark the alternatives.)


More information about the Python-list mailing list