Interesting problem comparing strings with integer values...

Carl Banks imbosol at
Thu Jan 16 01:17:09 CET 2003

Chris Spencer wrote:
>        Due to certain design constraints, I must be able to store
> both integers and floating point numbers as strings.  These strings
> must be able to be compared correctly, so things like: "999"<"3432"
> are not possible.
>        One option we thought of was padding the strings with zeros,
> so things like: "00000999"<"00003432" would work.  This seems a bit
> hack-y to me.  I was wondering if anyone has a more elegant solution
> to the problem?

1. Go back to your client/boss and tell him/her that his/her design
   contraint sucks because it is counterproductive (politely).

2. Use Perl.  (That's probably what your cognitive dissonant
   client/boss is trying to make you do anyways.)

3. Subclass str in Python 2.2 and above.  Redefine __cmp__ to
   compare strings numerically, and probably you should redefine
   __init__ to enforce an invariant that the string must hold a
   numerical value.

4. Instead of using operators, define some functions to do string
   comparisons for you.


More information about the Python-list mailing list