0% found this document useful (0 votes)
38 views4 pages

8 - Python Basic Examples

Uploaded by

fersd2018
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views4 pages

8 - Python Basic Examples

Uploaded by

fersd2018
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

8.

Python basic examples


While most examples will be file-oriented the same data-processing principles can be applied to
network equipment. Only part with reading from file will be replaced to get output from hardware.

Formatting lines with f-strings


The f-strings allow not only to set values to template but also to perform calls to
functions, methods, etc.
In many situations f-strings are easier to use than format and f-strings work faster than
format and other methods of string formatting.
ip = '10.1.1.1'
mask = 24

print(f"IP: {ip}, mask: {mask}")


# 'IP: 10.1.1.1, mask: 24'

In addition to substituting variable values you can write expressions in curly braces:
octets = ['10', '1', '1', '1']
mask = 24
f"IP: {'.'.join(octets)}, mask: {mask}"
# 'IP: 10.1.1.1, mask: 24'

After colon in f-strings you can specify the same values as in format:
oct1, oct2, oct3, oct4 = [10, 1, 1, 1]
print(f'''
IP address:
{oct1:<8} {oct2:<8} {oct3:<8} {oct4:<8}
{oct1:08b} {oct2:08b} {oct3:08b} {oct4:08b}''')

# IP address:
# 10 1 1 1
# 00001010 00000001 00000001 00000001

When using f-strings in loops an f-string must be written in body of the loop to «catch» new
variable values within each iteration:
ip_list = ['10.1.1.1/24', '10.2.2.2/24', '10.3.3.3/24']
for ip_address in ip_list:
ip, mask = ip_address.split('/')
print(f"IP: {ip}, mask: {mask}")

45
Variable unpacking
Variable unpacking is a special syntax that allows to assign elements of an iterable to
variables.
Example of variable unpacking:
interface = ['FastEthernet0/1', '10.1.1.1', 'up', 'up']
intf, ip, status, protocol = interface
print(intf) # 'FastEthernet0/1'

When you unpack variables, each item in list falls into the corresponding variable. It is
important to take into account that there should be exactly as many variables on the left as
there are elements in the list.
If amount of variables are less or more, there will be an exception.

Use *
Variable unpacking supports a special syntax that allows unpacking of several elements
into one. If you put * in front of variable name, all elements except those that are explicitly
assigned will be written into it.

For example, you can get the first element in first variable and the rest in rest:
vlans = [10, 11, 13, 30]
first, *rest = vlans
print(first) # 10
print(rest) # [11, 13, 30]

List, dict, set comprehensions


Python supports special expressions that allow for compact creation of lists, dictionaries,
and sets:
• list comprehensions
• dict comprehensions
• set comprehensions

These expressions not only enable more compact objects to be created but also create
them faster. Although they require a certain habit of use and understanding at first, they
are very often used.

List comprehensions
List comprehension is an expression like:

46
vlans = [f'vlan {num}' for num in range(10, 16)]
print(vlans)
# ['vlan 10', 'vlan 11', 'vlan 12', 'vlan 13', 'vlan 14', 'vlan
15']

The previous example could be done like this:


vlans = []
for num in range(10, 16):
vlans.append(f'vlan {num}')

In list comprehensions you can use if :


items = ['10', '20', 'a', '30', 'b', '40']

only_digits = [int(item) for item in items if item.isdigit()]

print(only_digits) # [10, 20, 30, 40]

The previous example could be done like this:


items = ['10', '20', 'a', '30', 'b', '40']
only_digits = []

for item in items:


if item.isdigit():
only_digits.append(int(item))

Dict comprehensions
Dict comprehensions are similar to list comprehensions but they are used to create
dictionaries. For example, the expression:
d = {}
for num in range(1, 11):
d[num] = num**2

print(d)
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10:
100}

Can be replaced with a dict comprehension:


d = {num: num**2 for num in range(1, 11)}

47
Another example in which you need to change an existing dictionary and convert all keys
to lowercase. First, a solution without a dict comprehension:
r1 = {'IOS': '15.4',
'IP': '10.255.0.1',
'hostname': 'london_r1',
'location': '21 New Globe Walk',
'model': '4451',
'vendor': 'Cisco'}

lower_r1 = {}
for key, value in r1.items():
lower_r1[key.lower()] = value
print(lower_r1)

Dict comprehension version:


r1 = {'IOS': '15.4',
'IP': '10.255.0.1',
'hostname': 'london_r1',
'location': '21 New Globe Walk',
'model': '4451',
'vendor': 'Cisco'}

lower_r1 = {key.lower(): value for key, value in r1.items()}


print(lower_r1)

Set comprehensions
Set comprehensions are generally similar to list comprehensions. For example, get a set
with unique VLAN numbers:
vlans = [10, '30', 30, 10, '56']

unique_vlans = {int(vlan) for vlan in vlans}


print(unique_vlans) # {10, 30, 56}

48

You might also like