Getting a unknown word out of a list with no spaces
Fredrik Lundh
fredrik at pythonware.com
Thu Jul 17 05:41:41 EDT 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] == "<"
False
>>> ""[:1] == "<"
False
(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.)
</F>
More information about the Python-list
mailing list