Site icon Karneliuk

CEX (Code EXpress) 05. From lists to separate variables and back.

Hello my friend,

So far, we have covered the separate variables and the list variables in the Python 3.8. Before we go further, it makes sense how you can convert one type of the variables to another. Therefore, we discuss this topic today.  

Network automation training – boost your career

Don’t wait to be kicked out of IT business. Join our network automation training to secure your job in future. Come to NetDevOps side.

How does the training differ from this blog post series? Here you get the basics and learn some programming concepts in general, whereas in the training you get comprehensive set of knowledge with the detailed examples how to use Python for the network and IT automation. You need both.

What are we going to do today?

Working with variables is an essential part of any programming language including Python. Part of such a work is a conversion of a variable of one type to another and back. That’s why we will explore today the following functions:

Sounds simple? It absolutely could be; however, this is very useful and handy approach.

Why does it matter?

One of the very often task in the programming, especially in the network automation, where Python plays a significant role, is a working with tables. By tables we mean real tables, which people work with using the table editors such as Excel or any other similar tool. The working with tables is quite an old method, though still widely used. Moreover, it is (arguably) convenient method of passing data between different applications, when there is no API created and the development of a new one doesn’t make economic sense. 

Reading/writing from/to file is out of scope for this blogpost. However, it will be covered in upcoming series.

One of the most widely supported table formats is a CSV, what stands for Comma-Separated Values. As you see from its name, the columns in such a table are split using the comma. Therefore, using the mentioned split() and join() functions you can convert each string in a set of variables and other way around.

Working with tables is not a single use case for these functions. The following list gives you some more insights:

Obviously, this list is by no mean exhaustive. Based on your experience, we are pretty confident, you can find much more examples.

How are we doing that?

Following the approach, we have started earlier, we create a new directory in our GitHub Python’s lessons:


1
2
3
4
$ cd CEX
$ mkdir 05
$ cd 05
$

Inside the directory we create a new file called lists.py, which we will use during this class:


1
2
3
$ touch vars.py && chmod a+x vars.py
$ cat vars.py
#!/usr/local/bin/python3.8

If you have a question to chmod command or to the path to the Python interpreter, take a look on the corresponding class.

#1. Using split() function

Let’s start with the creation of an input string with some parameters in CSV-table style:


1
2
3
4
$ cat vars.py
#!/usr/local/bin/python3.8

initial_string = 'pe1-fra-de,Equinix FR5,10.11.12.13/24,,Cisco NCS 5500'

The provided string contains the parameters, such a device’s hostname, its location, management IP address, some missing parameter and the device type. 

In one of the previous blogposts we’ve explained the string variables in greater details.

Using split() function you can turn that sting into a list of elements as demonstrated below:


1
2
3
4
5
6
7
8
$ cat vars.py
#!/usr/local/bin/python3.8

initial_string = 'pe1-fra-de,Equinix FR5,10.11.12.13/24,,Cisco NCS 5500'

dev_params = initial_string.split(',')

print('The variables is split into: {}'.format(dev_params))

The function is applied to the variable initial_string. You can notice that in the snippet in the initial_string.split(‘,’) construction, where the separator ‘,’ is provided as an input to split() function. The result of the Python 3.8 code’s execution you can find in the next output:


1
2
$ ./vars.py
The variables is split into: ['pe1-fra-de', 'Equinix FR5', '10.11.12.13/24', '', 'Cisco NCS 5500']

All the columns, even an empty one, are successfully converted into an element in the list.

In one of the previous blogposts we’ve explained the list in greater details.

If your logic requires to create a separate variable rather than a list, you can do that as well:


1
2
3
4
5
6
7
8
9
10
11
12
$ cat vars.py
#!/usr/local/bin/python3.8

initial_string = 'pe1-fra-de,Equinix FR5,10.11.12.13/24,,Cisco NCS 5500'

dev_params = initial_string.split(',')

print('The variables is split into: {}'.format(dev_params))

ip_addr, ip_prefix = dev_params[2].split('/')

print('The IP address is {} with the prefix {}'.format(ip_addr, ip_prefix))

In this example you can see the Python’s function split() having another separator ‘/’ being applied to an element from the created list dev_params. However, this time you can see that the result of the function’s execution is assigned to two variables, what results in assigning the specific value to each variable. Let’s verify how that works:


1
2
3
$ ./vars.py
The variables is split into: ['pe1-fra-de', 'Equinix FR5', '10.11.12.13/24', '', 'Cisco NCS 5500']
The IP address is 10.11.12.13 with the prefix 24

As you might have noticed, the input to the split() function is a separator, and any character could be a separator.

To give you some formal summary, the syntax of the split function is the following result_list = string_to_split.split(‘separator’), where:

Heading further from separation to an aggregation. 

#2. Using join() function

The Python’s join() function is used to turn an input list into a single string by connecting the elements to each other using a specific conjunction symbol. Its syntax is an opposite to the one you have seen for split(), and to be honest quite a misleading in the beginning. The join() function is used in the Python’s construction result_string = ‘aggregator’.join(list_to aggegate), where:

The best way to describe how it works is an example. Therefore, our Python’s 3.8 script has an extension containing the join() function:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$ cat vars.py
#!/usr/local/bin/python3.8

initial_string = 'pe1-fra-de,Equinix FR5,10.11.12.13/24,,Cisco NCS 5500'

dev_params = initial_string.split(',')

print('The variables is split into: {}'.format(dev_params))

ip_addr, ip_prefix = dev_params[2].split('/')

print('The IP address is {} with the prefix {}'.format(ip_addr, ip_prefix))

final_string = ','.join(dev_params)

print('The string joined back: {}'.format(final_string))

The result of this Python’s 3.8 script execution you can find below:


1
2
3
4
$ ./vars.py
The variables is split into: ['pe1-fra-de', 'Equinix FR5', '10.11.12.13/24', '', 'Cisco NCS 5500']
The IP address is 10.11.12.13 with the prefix 24
The string joined back: pe1-fra-de,Equinix FR5,10.11.12.13/24,,Cisco NCS 5500

The string is composed back out of the list, and, as you see, it is equal to the original one, as it includes all the proper columns (even the columns with the missing elements).

Much in the similar way, when you can use split() function to assign values to separate variables, you can use join() to merge multiple separate value together. However, the join() function allows to have only one argument provided, which must be a list. To overcome this issue, you need to specify all the variables you want to unite into a list format:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$ cat vars.py
#!/usr/local/bin/python3.8

initial_string = 'pe1-fra-de,Equinix FR5,10.11.12.13/24,,Cisco NCS 5500'

dev_params = initial_string.split(',')

print('The variables is split into: {}'.format(dev_params))

ip_addr, ip_prefix = dev_params[2].split('/')

print('The IP address is {} with the prefix {}'.format(ip_addr, ip_prefix))

final_string = ','.join(dev_params)

print('The string joined back: {}'.format(final_string))

ip_addr_pref = '/'.join([ip_addr, ip_prefix])

print('The IP address and prefix together is {}'.format(ip_addr_pref))

You see that the two variables, which are intended to be merged are put in the list [ip_addr, ip_prefix], which is itself an input to the join() function.

The result of this function (we bet that you can already predict) is the following:


1
2
3
4
5
$ ./vars.py
The variables is split into: ['pe1-fra-de', 'Equinix FR5', '10.11.12.13/24', '', 'Cisco NCS 5500']
The IP address is 10.11.12.13 with the prefix 24
The string joined back: pe1-fra-de,Equinix FR5,10.11.12.13/24,,Cisco NCS 5500
The IP address and prefix together is 10.11.12.13/24

And comparing the join() to split() again, the aggregator could be any character based on your application’s logic.

Both separator and aggregator could be a variable.

If you prefer video

If you prefer watching the video instead of reading blogpost, that is also wonderful. We value your time and want to create for you the best experience possible. Therefore, for all the blogposts associated with CEX series, we will record the video and post it on our YouTube channel.

And here is the video for this blogpost (link).

What else shall you try?

Programming is all around testing, trying, breaking and fixing the things. Try to do the following things to collect some more experience:

Lessons in GitHub

You can find the final working versions of the files from this blog at our GitHub page.

Conclusion

Once you are getting more familiar with Python, and you are working more on the network automation tasks, you will use split() and join() functions quite often, as they form a basis of working with the table’s input or reports in the scripts. In the next couple of blogposts, you will see more real examples of these and other functions. Take care and goodbye!

Support us





P.S.

If you have further questions or you need help with your networks, I’m happy to assist you, just send me message. Also don’t forget to share the article on your social media, if you like it.

BR,

Anton Karneliuk 

Exit mobile version