#

Wednesday, February 5, 2025

Working with Strings in Python for Network Engineers

Strings are a Data Type in Python which is nothing but an ordered sequence of characters. They are also immutable which means they cannot be altered, you can only replace them completely.

We can use letters, numbers, special characters like underscore / dash etc or even spaces as a string. 

We can use both single quotation marks or double quotation marks to get same output. When you use three double quotation marks, you can get some interesting thing done.

As an example, let's say we want to push the following commands to a router.

router ospf 1
 network 10.0.0.0 0.0.0.255 area 0
 network 10.0.1.0 0.0.0.255 area 1

We can use the following method with \n in strings to separate lines and send "enter" key effect.

You can use triple quotation without \n to get the same output.








After it is compiled, following will be the output; what happens actually is it inserts \n automatically.






Converting/Casting Strings to Integers

There are some cases we need to convert between data types like strings to integers. As an example, we may get some information like IOS version number from a show version output which comes as a text  and will need to get into our program as an integer to run a comparison or do mathematical stuff with it. We can do this by converting string into integer by following way using some special functions.











Following is how to convert between strings, ints or floats using some other functions.

What should we keep in mind is that, it is possible.










Concatenation

This allows us to modify a String with adding some strings to it.
Following is an example.







Output will be;





It is a simple script which asks for a command to enter and adds enable, enter and the entered command ending with another enter. The + sign is the key of concatenation but all should be strings for this to work. Note that input function is getting the things entered by user as a String.

Formatting Strings

This does concatenation, changing Ints or Floats to String and all.
Let's see the following example.






When this piece of code is run, following will be the output,





It will ask for the hostname and version, and it will display it all as a String.

Following were some older ways of doing formatting,









Both the above methods are no longer used but can be seen on older written scripts.

No comments:

Post a Comment