Since hex does not have leading leading zeros, you can use zfill(2)
import string ip = raw_input('Enter IP') a = ip.split('.') b = hex(int(a[0]))[2:].zfill(2) + hex(int(a[1]))[2:].zfill(2) + hex(int(a[2]))[2:].zfill(2) + hex(int(a[3]))[2:].zfill(2) b = b.replace('0x', '') b = b.upper() print b
We take the hexadecimal number only with [2:] (delete '0x'), and then add only 2 leading zeros only if necessary.
Output Example:
Enter IP 192.168.2.1 C0A80201
Output Example:
Enter IP 115.255.8.97 73FF0861
Edit1:
by @volcano you can replace it with a list:
b = "".join([hex(int(value))[2:].zfill(2) for value in a])
source share