Ignore case in Python strings -
this question has answer here:
- how do case-insensitive string comparison? 10 answers
what easiest way compare strings in python, ignoring case?
of course 1 can (str1.lower() <= str2.lower()), etc., created 2 additional temporary strings (with obvious alloc/g-c overheads).
i guess i'm looking equivalent c's stricmp().
[some more context requested, i'll demonstrate trivial example:]
suppose want sort looong list of strings. thelist.sort(). o(n * log(n)) string comparisons , no memory management (since strings , list elements sort of smart pointers). happy.
now, want same, ignore case (let's simplify , strings ascii, locale issues can ignored). can thelist.sort(key=lambda s: s.lower()), cause 2 new allocations per comparison, plus burden garbage-collector duplicated (lowered) strings. each such memory-management noise orders-of-magnitude slower simple string comparison.
now, in-place stricmp()-like function, do: thelist.sort(cmp=stricmp) , fast , memory-friendly thelist.sort(). happy again.
the problem python-based case-insensitive comparison involves implicit string duplications, expecting find c-based comparisons (maybe in module string).
could not find that, hence question here. (hope clarifies question).
in response clarification...
you use ctypes execute c function "strcasecmp". ctypes included in python 2.5. provides ability call out dll , shared libraries such libc. here quick example (python on linux; see link win32 help):
from ctypes import * libc = cdll("libc.so.6") // see link above win32 libc.strcasecmp("this", "this") // returns 0 libc.strcasecmp("this", "that") // returns 8
may want reference strcasecmp documentation
not sure faster or slower (have not tested), it's way use c function case insensitive string comparisons.
~~~~~~~~~~~~~~
activestate code - recipe 194371: case insensitive strings recipe creating case insensitive string class. might bit on kill quick, provide common way of handling case insensitive strings if plan on using them often.
Comments
Post a Comment