-1

How can i add zeros to the leading part in each byte of ip address using python so that each byte will always be in 3 digit format. The input and output should be like

1.2.3.4     ==>> 001.002.003.004
1.192.122.5 ==>> 001.192.122.005
192.168.1.1 ==>> 192.168.001.001
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Pratheesh
  • 565
  • 4
  • 19

5 Answers5

1

You can use this:

ip = '1.2.3.4'
'.'.join(i.zfill(3) for i in ip.split('.'))

'001.002.003.004'
luigigi
  • 4,146
  • 1
  • 13
  • 30
1

You could do this:

ip = '1.2.3.4'
print('.'.join([(3 - len(i)) * '0' + i for i in ip.split('.')]))

Output:

001.002.003.004
9769953
  • 10,344
  • 3
  • 26
  • 37
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

You can use zfill():

def addZeros(ip, zero_num = 3):
    parts = ip.split('.')
    parts = [part.zfill(zero_num) for part in parts]
    return '.'.join(parts)
    
print(addZeros('1.2.3.4'))
# 001.002.003.004
Kien Nguyen
  • 2,616
  • 2
  • 7
  • 24
  • 1
    If you make it a function `addZeros`, perhaps it's nicer to specify how many zeros are to be added (or rather, the value of `zfill`) as a function argument (with a default value). – 9769953 Jan 22 '21 at 07:55
  • @00 You're right. I will edit my answer. – Kien Nguyen Jan 22 '21 at 08:02
0
def zero_adder(digit):
    if len(digit) == 3:
        return digit
    return zero_adder("0" + str(digit))

ips = ["1.192.122.5", "192.168.1.1", "1.2.3.4"]
output = []
for ip in ips:
    ips_with_zero = []
    for num in ip.split("."):
        ips_with_zero.append(zero_adder(num))
    output.append(".".join(ips_with_zero))
print(output)
bilke
  • 415
  • 3
  • 6
0

You could use an f-string with proper format:

ip = '.'.join(f'{int(n):03d}' for n in ip.split('.'))
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50