Interesting problem comparing strings with integer values...

Chad Netzer cnetzer at mail.arc.nasa.gov
Wed Jan 15 19:02:59 EST 2003


On Wednesday 15 January 2003 15:23, 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?

If you must only store the numbers as strings, then you could easily 
convert them back to number types for comparisons, ie:

float("999") < float("3432")

A fancy method would be to try converting to floats, and if that fails, 
convert to longs for comparison.  If this approach isn't workable, then 
you need to more clearly identify your needs.  Is speed an issue?  Is 
it really only an issue of storing data as strings, or must you operate 
directly on those strings as well, etc.?  And will the numbers all be 
small (floats loose precision as they get to be very large, for example)

-- 
Bay Area Python Interest Group - http://www.baypiggies.net/

Chad Netzer
cnetzer at mail.arc.nasa.gov





More information about the Python-list mailing list