string compare question.Please Help!!!
Don O'Donnell
donod at home.com
Tue Dec 25 12:36:46 EST 2001
Evgeny Jonson wrote:
>
> #For IP addres something like this:
>
> import string
> import sys
>
> def ip_cmp(ip1, ip2):
> """Compare IP addreses as strings
> """
> l_ip1 = ip1.split('.')
> l_ip2 = ip2.split('.')
> if len(l_ip1) == 4 and len(l_ip2) == 4:
> s_ip1 = string.zfill(l_ip1[0], 3) + '.' + \
> string.zfill(l_ip1[1], 3) + '.' + \
> string.zfill(l_ip1[2], 3) + '.' + \
> string.zfill(l_ip1[3], 3)
>
> s_ip2 = string.zfill(l_ip2[0], 3) + '.' + \
> string.zfill(l_ip2[1], 3) + '.' + \
> string.zfill(l_ip2[2], 3) + '.' + \
> string.zfill(l_ip2[3], 3)
> resault = cmp(s_ip1, s_ip2)
> else:
> print 'Wrong IP addres format!'
> sys.exit(0)
>
> return resault
>
> # my test
>
> print ip_cmp('10.66.73.78','10.0.0.0') # return 1
> print ip_cmp('10.66.73.78','10.255.255.255') # return -1
The concept is right but the implementation is tiresome.
There is no need to convert the list back to a string,
just compare the two lists.
Here is a quicker way:
>>> def ipnumlist(ipstr):
"""Convert an ip address to a list of integers"""
return [int(s) for s in ipstr.split('.')]
>>> cmp(ipnumlist('10.66.73.78'), ipnumlist('10.255.255.255'))
-1
And, if you want to package the compare into a function:
>>> def ipcmp(ip1, ip2):
return cmp(ipnumlist(ip1), ipnumlist(ip2))
>>> ipcmp('10.66.73.78', '10.255.255.255')
-1
>>> ipcmp('10.66.73.78', '10.55.255.255')
1
Cheers,
Don
More information about the Python-list
mailing list