In the second part of assignments for the first week of Kirk Byers Python for Network Engineers class we will be working with IPv6 addresses.
We start with the following IPv6 address: FE80:0000:0000:0000:0101:A3EF:EE1E:1719.
The goal is then to split this address into individual parts. The delimiter in an IPv6 address is a colon. For an IPv4 address we would have used a dot instead. Python has a built-in function for splitting strings. To split the address we use this function and tell Python that a colon is our delimiter.
print("IPv6 address split:") print(ipv6_split) print(type(ipv6_split))
This means that we have turned our string into a list, consisting of eight parts of the IPv6 address.
[email protected]:~/python/Week1$ python3 ipv6.py IPv6 address split: ['FE80', '0000', '0000', '0000', '0101', 'A3EF', 'EE1E', '1719']
To rejoin the address again the built-in function “join()” will be used. The syntax for this function is a bit awkward besides that it’s easy to use.
ipv6_new = ":".join(ipv6_split) print("IPv6 address rejoined:") print(ipv6_new) print(type(ipv6_new))
First we tell Python to put a colon between all the parts we are joining. The output then looks like this:
[email protected]:~/python/Week1$ python3 ipv6.py IPv6 address rejoined: FE80:0000:0000:0000:0101:A3EF:EE1E:1719
Note that the rejoined address now is a string. It would also be possible to rejoin with something else than a colon. Imagine that we have an MAC address taken from a Cisco device with the “show mac address-table” command. It’s in Cisco format, something like “0001.0002.0003”. We then want to take this MAC and use it in another device which uses colon as delimiter for MAC addresses. We could then first split the MAC into three parts by telling Python that the delimiter is a dot.
cisco_mac = "0001.0002.0003" cisco_mac_split = cisco_mac.split(".")
We could then rejoin the MAC address but using a colon as a delimiter and print that.
other_mac = ":".join(cisco_mac_split) print(other_mac)
The output of this is then:
[email protected]:~/python/Week1$ python3 mac.py 0001:0002:0003
There are better ways of doing this by leveraging modules but the goal here was to demo how easy and powerful it is to use the built-in functions “split()” and “join()”.
The code for this weeks assignment is available at my Github.
See you soon again!