[python] String slicing

Just learned a new technique…

physical_address = 'Physical Address. . . . . . . . . : 38-00-25-9F-58-30'

# Get only the mac address
print(physical_address.split()[-1])

This technique is very smart, first arrange the string into a list by using split method, the split method will store each string into a list when a whitespace is found.
['Physical', 'Address.', '.', '.', '.', '.', '.', '.', '.', '.', ':', '38-00-25-9F-58-30']
Then return the last element of the list by using [-1]

So by expanding this knowledge, I can change the mac address representation on different operating systems.

physical_address = 'Physical Address. . . . . . . . . : 38-00-25-9F-58-30'

# Get only the mac address
# Windows mac address format
mac_address_windows = physical_address.split()[-1]

# Linux mac address format
mac_address_linux = mac_address_windows.replace('-', ':')

# Cisco's mac address format
mac_address_cisco = mac_address_windows.replace('-', '')
mac_address_cisco = mac_address_cisco[0:4] + '.' + mac_address_cisco[4:8] + '.' + mac_address_cisco[8:12]

print(mac_address_windows)
print(mac_address_linux)
print(mac_address_cisco.lower())

Result will look like this:
slicing1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s