string compare question.Please Help!!!

I.J. shiver at yubc.net
Tue Dec 25 06:47:06 CET 2001


If you ar trying to compare strings as if they are numbers, you cant!
>>>cmp('10.66.73.78','10.255.255.255')
1
because when comparing strings, comparation begins from first characters of both strings and continues until ascii values are diferent, like sorting of filenames...
So '1' is equal to '1', '0' is equal to '0', '.' is equal to '.' but '6' has greater ascii than '2', and cmd() returns 1.
In the same way '2' is greater than '100'.
This should work
ip1,ip2='10.66.73.78','10.255.255.255'
#split string into four substrings
ip1,ip2=ip1.split( '.'),ip2.split( '.')
#convert strings into numbers
ip1,ip2=[long(elem) for elem in ip1],[long(elem) for elem in ip2]
true=0
#compare numbers
for n in range(4):
    if ip1[n]>ip2[n]:
        true=1
        break
    elif ip1[n]<ip2[n]:
        true=-1
        break
true should now be -1

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20011225/ae912c5f/attachment.html>


More information about the Python-list mailing list