0

My file contains IP addresses that I'd like to convert to host names. The IP addresses are the same except for the last three octets. For example:

192.168.38.8
192.168.38.9
192.168.38.10

I have the following code in my python script to substitute the IP address with the host name which ends in the final octet.

 hostname = re.sub('192.168.38.','Host-Name',lm.group(4))

This give me the results:

Host-Name8
Host-Name9
Host-Name10

How do I get the single digit octets to have a leading zero? The desired output would be;

Host-Name08
Host-Name09
Host-Name10
teamg
  • 703
  • 2
  • 9
  • 15
  • Possible duplicate of [Best way to format integer as string with leading zeros?](https://stackoverflow.com/questions/733454/best-way-to-format-integer-as-string-with-leading-zeros) – Barmar Sep 07 '17 at 16:11
  • ideally, it should consider **3** digits, according to octet size. `Host-Name008` ... – RomanPerekhrest Sep 07 '17 at 16:12
  • 1
    Possible duplicate of [Display number with leading zeros](https://stackoverflow.com/questions/134934/display-number-with-leading-zeros) – CDspace Sep 07 '17 at 16:14

2 Answers2

0

re.sub isn't used correctly.

From documentation for re.sub, you can pass a string or replacement function that returns a string when a match is found.

Notice: You can use any of the methods in answers to questions in the duplicate flags to pad single digits.

def replace_ip(match):
    last_octet = match.group(1)

    return "".join((
        'Host-Name',
        last_octet.zfill(2)
    ))


re.sub(r'192.168.38.(\d+)', replace_ip, ips_from_file)
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Oluwafemi Sule
  • 36,144
  • 1
  • 56
  • 81
0

You might find just using split() easier as follows:

for ip_addr in ["192.168.38.8", "192.168.38.9", "192.168.38.10"]:
    print "Host-Name{:02}".format(int(ip_addr.split('.')[3]))

This would give you:

Host-Name08
Host-Name09
Host-Name10
Martin Evans
  • 45,791
  • 17
  • 81
  • 97