Book Image

Mastering Python Scripting for System Administrators

By : Ganesh Sanjiv Naik
Book Image

Mastering Python Scripting for System Administrators

By: Ganesh Sanjiv Naik

Overview of this book

Python has evolved over time and extended its features in relation to every possible IT operation. Python is simple to learn, yet has powerful libraries that can be used to build powerful Python scripts for solving real-world problems and automating administrators' routine activities. The objective of this book is to walk through a series of projects that will teach readers Python scripting with each project. This book will initially cover Python installation and quickly revise basic to advanced programming fundamentals. The book will then focus on the development process as a whole, from setup to planning to building different tools. It will include IT administrators' routine activities (text processing, regular expressions, file archiving, and encryption), network administration (socket programming, email handling, the remote controlling of devices using telnet/ssh, and protocols such as SNMP/DHCP), building graphical user interface, working with websites (Apache log file processing, SOAP and REST APIs communication, and web scraping), and database administration (MySQL and similar database data administration, data analytics, and reporting). By the end of this book, you will be able to use the latest features of Python and be able to build powerful tools that will solve challenging, real-world tasks
Table of Contents (21 chapters)

Strings

Like numbers, strings are also one of the data structures in Python. Python can manipulate strings. Strings can be expressed as follows:

  • Enclosed in single quotes ('...')
  • Enclosed in double quotes ("...")

See the following example:

>>> 'Hello Python'
'Hello Python'
>>> "Hello Python"
'Hello Python'

A string is a set of characters. We can access the characters one at a time, as follows:

>>> city = 'delhi'
>>> letter = city[1]
>>> letter = city[-3]

In the second statement, we are selecting the character number 1 from city and assigning it to letter. The number in those square brackets is an index. The index indicates which character you want to access. It starts from 0. So, in the preceding example, when you will execute letter = city[1], you will get the following output:

city d e l h i
index 0 1 2 3 4
-5 -4 -3 -2 -1

Output:
e
l

Concatenation (+) and repetition (*)

Next, comes concatenation and repetition. Refer to the following code:

>>> 3 * 'hi' + 'hello'
'hihihihello'

In the preceding example, we are doing string concatenation and repetition. 3 * 'hi' means hi gets printed 3 times and, using the + sign, we are joining the hello string next to hi.

We can automatically concatenate two strings just by writing them next to each other. These two strings must be enclosed between quotes, as shown here:

>>> 'he' 'llo'
'hello'

This feature is really helpful when you have long strings and you want to break them. Here is an example:

>>> str = ('Several strings'
... 'joining them together.')
>>> str
'Several strings joining them together.'

String slicing

Strings support slicing, which means getting characters by a specified range from your string. Let's take a look at the following example. Note that starting index value is always included and an end value is always excluded.

Consider a string, str = "Programming":

>>> str[0:2]
'Pr'
>>> str[2:5]
'ogr'

Now, the default of an omitted first index is zero, as in the example:

>>> str[:2] + str[2:]
'Python'
>>> str[:4] + str[4:]
'Python'
>>> str[:2]
'Py'
>>> str[4:]
'on'
>>> str[-2:]
'on'

Accessing values in strings

We can access characters from strings using slicing by using square brackets. We can also access characters from strings between the specified range. Refer to the following example:

#!/usr/bin/python3
str1 = 'Hello Python!'
str2 = "Object Oriented Programming"
print ("str1[0]: ", str1[0])
print ("str2[1:5]: ", str2[1:5])

Output:
str1[0]: H
str2[1:5]: bjec

Updating strings

We can update a string by reassigning a new value to the specified index. Refer to the following example:

#!/usr/bin/python3
str1 = 'Hello Python!'
print ("Updated String: - ", str1 [:6] + 'John')

Output:
Updated String: - Hello John

Escape characters

Python supports escape characters that are non-printable and can be represented with a backslash notation. An escape character gets interpreted in both single and double quoted strings:

Notations

Hex characters

Description

a

0x07

Bell or alert

b

0x08

Backspace

cx

Control-x

n

0x0a

Newline

C-x

Control-x

e

0x1b

Escape

f

0x0c

Form feed

s

0x20

Space

M-C-x

Meta-control-x

x

Character x

nnn

Octal notation, where n is in the range 0.7

r

0x0d

Carriage return

xnn

Hexadecimal notation, where n is in the range 0.9, a.f, or A.F

t

0x09

Tab

v

0x0b

Vertical tab

Special string operators

The following table shows string's special operators. Consider a is Hello and b is World:

Operator

Description

Example

+

Concatenation: adds values on either side of the operator

a + b will give HelloWorld

[]

Slice: gives the character from the given index

a[7] will give r

[ : ]

Range slice: gives the characters from the given range

a[1:4] will give ell

*

Repetition: creates new strings, concatenating multiple copies of the same string

a*2 will give HelloHello

not in

Membership: returns true if a character does not exist in the given string

Z not in a will give 1

in

Membership: returns true if a character exists in the given string

H in a will give 1

%

Format: performs string formatting

% string formatting operator

% is a string formatting operator in Python. Refer to the following example:

#!/usr/bin/python3
print ("Hello this is %s and my age is %d !" % ('John', 25))


Output:
Hello this is John and my age is 25 !

The following table shows a list of symbols used along with %:

S.No.

Format symbol and conversion

1

%c – character

2

%s – string conversion via str() prior to formatting

3

%i – signed decimal integer

4

%d – signed decimal integer

5

%u – unsigned decimal integer

6

%o – octal integer

7

%x – hexadecimal integer (lowercase letters)

8

%X – hexadecimal integer (uppercase letters)

9

%e – exponential notation (with lowercase e)

10

%E – exponential notation (with uppercase E)

11

%f – floating point real number

Triple quotes in Python

Python's triple quotes functionality for strings is used to span multiple lines, including newlines and tabs. The syntax for triple quotes consists of three consecutive single or double quotes. Refer to the following code:

#!/usr/bin/python3

para_str = """ Python is a scripting language which was created by
Guido van Rossum in 1991, t which is used in various sectors such as Game Development, GIS Programming, Software Development, web development,
Data Analytics and Machine learning, System Scripting etc.
"""
print (para_str)

It produces the following output. Note the tabs and newlines:

Output:
Python is a scripting language which was created by
Guido van Rossum in 1991, which is used in various sectors such as
Game Development, GIS Programming, Software Development, web development,
Data Analytics and Machine learning, System Scripting etc.

Strings are immutable

Strings are immutable, meaning we can't change the values. Refer to the given example:

>>> welcome = 'Hello, John!'
>>> welcome[0] = 'Y'
TypeError: 'str' object does not support item assignment

As the strings are immutable; we cannot change an existing string. But we can create a new string that will be different from the original:

>>> str1 = 'Hello John'
>>> new_str = 'Welcome' + str1[5:]
>>> print(str1)
Hello John
>>> print(new_str)
Welcome John
>>>