Python for Network Engineers: String Manipulation

Hello friends, and welcome to another update of my blog series: Python for Network Engineers. Today, we will be learning about String Manipulation in Python. This is an important topic for every aspiring network programmer as majority of the time spent in programming for networks with Python, is handling and manipulating String outputs.

Assigning values to a Python string variable is straightforward: variable_name = “my string here”. In Python, a String is an object that works similarly like an array of characters. What I mean by that is, each character in a string has its own index value which lets you identify each character in a string and perform functions with them. Below is a list of common string methods and how they work.

Length of Characters in a String

More often than not, you’ll want to know how many characters there are in your string. This is achieved by using len() method. Try the script below on your IDLE and the result should be 21, as there are 21 characters in the string “hello wonderful world”.

my_string = 'hello wonderful world'
len(my_string)
#returns 21

Not to be confused with count(), which is a method to count how many times a character is found in the string. This method requires a string parameter. Below script returns 2, as the character ‘e’ appears twice (2 times) in the string “hello wonderful world”.

my_string.count('e')
#returns 2

String Lowercase and Uppercase

If you want to change the string into lowercase or uppercase, you can do so by using the methods lower() and upper() respectively. The important thing to note here is that, these methods do not actually change the value. Check out the example in my screenshot below and see that the original value is unchanged.

my_string.lower()
my_string.upper()

String startswith() and endswith()

Another handy method is to identify whether a string starts or ends with a specific character. The methods are appropriately named startswith() and endswith(). Both methods return Boolean (True or False).

my_string.startswith('h') #true
my_string.startswith('j') #false
my_string.endswith('e') #false
my_string.endswith('d') #true

String stripping

If you want to remove certain leading and trailing characters from your string, the strip() method is your friend. Without any parameter, the method removes whitespaces and returns your string whitespace-free. You may specify the character you want to remove, in the parameters. In the example below, the method removes all the leading and trailing whitespace. The next example specifies a character to remove.

my_string = '   hello wonderful world ' 
#returns 'hello wonderful world'

new_string = 'hello world'
new_string.strip('h')
#returns 'ello world'

It is important to note, that strip only removes leading and trailing characters. If you want to remove characters within the string, like somewhere in the middle, you’ll want to use the method replace(). This method accepts the first parameter as the existing character you want to replace. The second parameter is the new character you want to replace it with. In the example below, we are removing the space between ‘hello’ and ‘world’.

my_string = 'hello world'
my_string.replace(' ','')
#returns 'helloworld'

String Split and Join

Now we will look at how to split a string. But first, why do we want to split a string? In this example, our string has a list of names separated by spaces. We want to be able to use each name, without calling for the entire string, or just a single character. This is where we use the method split().

my_string = 'apple banana orange'
my_string.split()
#returns ['apple', 'banana', 'orange']

#you can store this new value into another string
new_string = my_string.split()
new_string[1]
#returns banana
new_string[0]
#returns apple

#you can specify a delimiter too
my_string = 'london,tokyo,paris'
my_string.split(',')
#returns ['london', 'tokyo', 'paris']

There’s a lot more methods available to use in String handling and manipulation but these are the most common that you will be using in Network Programming. For a list of methods available for Python string, visit this link. I hope you learned something new today friend! In the coming days, we will be learning Python Math operations and Booleans. See you again soon!

Python for Network Engineers: Basic Scripting

Hello friends and welcome to my blog series guide on network programming. Previously, I shared a short overview of how Python is useful for network engineers and Python data types. Today, we will explore Python scripting and make short scripts of our own. This post assumes you already have Python in your operating system and is familiar with IDLE (Python IDE that comes with Python installation).

Hello World

First we will learn how to output ‘hello world’. In your command line, use the print method below and hit enter (screenshot using IDLE). print() is a Python method to output something.

print('hello world')

User Input

Next, we will ask the user to input their name, save it into a variable. We will then output the name back to the user. This time, we are using the method input().

my_name = input('Please enter your name: ')
#asks the user to input their name and stores it into the variable my_name

Basic Ping Script

Now we will write a multi-line script and save it into a python file. This script will ask the user to input an IP address. The script then pings that IP address 4 times and displays the result to the user. Don’t worry too much about the methods used to run the ping test. The goal of this is to familiarize yourself with how to create a Python script.

Using IDLE, create a new file (File > New File) and write the code snippet below. Press F5 so IDLE will save this file in your local drive. Notice the file extension (.py) – this is your first python script file.

import os

ipaddr = input('Enter the IP address:')
stream = os.popen('ping {}'.format(ipaddr))
output = stream.read()

if '0 received' in output:
    print('IP unreachable')
else:
    print('IP reachable')

print(output)

After saving, IDLE automatically runs the script for you to test.

You can also run this script from your command prompt (Windows) or Terminal (Mac OS). Remember you saved your python script file? Make sure you are in the same folder as your python file. You can use ‘cd’ to change directory like how I did in below screenshot.

If you’ve reached this far and successfully created and ran your python script, congratulate yourself. In the coming days, we will explore Python strings and learn how to handle and manipulate them for all our needs. See you again soon!

Python for Network Engineers: What & Why, Data Types

Hello friends and welcome to the first in my blog series of Python for Network Engineers. Today, we will start with the ‘what’ and ‘why’ and some basics of Python to help get you started in your learning journey to becoming a network programmer.

Requirements

Before we start, you must be equipped with the following to at least understand what I’m talking about. This blog is specifically for learning Python exclusively for the network engineering environment. If that’s where you belong, then this guide can help you.

  • You must already know the basic concepts of programming (i.e., variables, data types, conditionals, loops, methods and functions, etc.)
  • You must already know the basic concepts of computer networking (LAN/WAN, IP addressing, OSI model, etc.)

Why Python for Network Programming?

Python’s standard library has full support for computer networking (i.e., network protocols and other network concepts). It lets you access low level socket support in the underlying operating system, for connection-oriented and connectionless protocols. It also lets you access high level application protocols such as HTTP, FTP, etc.

What Python Can Do

Python scripting covers a wide range of support to computer networks from basic network automation, to enterprise-scale network polling (i.e., graphs for network monitoring). For example, my latest project involves creating a web UI for collecting device logs for Cisco and Juniper routers – all done with Python.

In this basic guide, we will learn all there is to know to start programming for computer networks using Python. Let’s jump start into our first concept, data types.

Python Data Types

In Python, a data type can be mutable or immutable. Mutable means, the value of an object can be changed. Alternatively, immutable means otherwise. It is similar to the concept of variables and constants. However, in Python, when you assign a new value to an existing variable (with immutable data type), rather than the object getting an updated value, a new object is created entirely.

Below is a list of Python Data Types and whether or not they are mutable.

MutableImmutable
ListBoolean
SetInteger
DictionaryFloating-point Numbers
Complex Numbers
String
Tuple
Frozen Set
There’s an in depth write up about the different Python Data Types and how they are used in this blog, if you wish to dive deeper.

In the next post, we will learn to use and manipulate String in Python. This is an important topic as majority of your time in network programming will be working with strings. I’ll see you again soon!

Introducing Myself

He shall be like a tree, planted by the rivers of water; that brings forth its fruit in its season; whose leaf also shall not wither; and whatever he does shall prosper – Psalm 1: 3

Hello there! My name is Abigail and you can call me Abi. I like to talk and I like to write. I like to think logically and engage in problem-solving activities. I work as a network operations engineer in a telecommunications company in Singapore.

What this blog will be about:

  • My journey to becoming a network programmer (learning Python, re-learning networking)
  • My journey in life

This blog is my lot in the cyber world and I hope to be able to share my learning progress and my life journey in general, to anyone who will find it helpful. In return, I’d like to continue progressing by reading and writing, and also learn from you, my reader. It’s a win win.

I have many dreams. One of which is to grow into a healthy and whole person, spiritually, physically and emotionally.

I am a Christian who believes that Jesus is the savior of mankind, and that He died and with His blood paid for all our sins, past, present and future. Through this blood, I am alive and by His grace I live.

I look forward to growing with you, in both network programming, in life and in Christ.