A curious bit of code...

Ethan Furman ethan at stoneleaf.us
Thu Feb 13 19:45:09 CET 2014


On 02/13/2014 10:37 AM, forman.simon at gmail.com wrote:
> I ran across this and I thought there must be a better way of doing it, but then after further consideration I wasn't so sure.
>
>    if key[:1] + key[-1:] == '<>': ...
>
>
> Some possibilities that occurred to me:
>
>    if key.startswith('<') and key.endswith('>'): ...
>
> and:
>
>    if (key[:1], key[-1:]) == ('<', '>'): ...
>
>
> I haven't run these through a profiler yet, but it seems like the original might be the fastest after all?

Unless that line of code is a bottleneck, don't worry about speed, go for readability.  In which case I'd go with the 
second option, then the first, and definitely avoid the third.

--
~Ethan~



More information about the Python-list mailing list