I am rather new to python and seeking help regarding a homework prompt of mine.
Here is the exact prompt from the professor:
Both start_ip and end_ip should be 12-digit integer numbers. That is to make the IP lookup easier. First split the ip address at periods, then add leading zeros to each number to make each of them three digits, i.e. the string 102.1.2.0 becomes the integer 102001002000. Hint: use the string zfill() method (zero fill) and do operations as strings to build a string of digits and only convert to an int after the whole number has been built (note that when converted to an int leading zeros of the first number will be lost since an int does not have leading zeros – that is OK).
So basically we remove the dots from the ip string, reformat the string to be 12 characters long, and then convert that to an int.
For example: 0.0.0.0 should go to -> 000.000.000.000 102.1.2.0 should go to -> 102001002000
This is what I came up with, but it doesnt seem to work:
def ip_to_int(ip):
ip = ip.split('.')
ip = ip[0].__str__() + ip[1].__str__() + ip[2].__str__() + ip[3].__str__()
ip = ip.zfill(12)
return int(ip)
For example, when I plug the ip 0.0.0.0 into this code, it returns the int 0. And when I put in 1.0.0.0 , it results in 1,000. I am not able to pinpoint why this is happening.
Like I said I am new to python so some of what I did might not entirely make sense.
Thanks in advance.
ip.zfill(12)is doing?ip[0]is already a string, no need to call:ip[0].__str__()and etcnote that when converted to an int leading zeros of the first number will be lost since an int does not have leading zeros – that is OK)And so0.0.0.0should be0, correct?