Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Python Scripting for System Administrators

You're reading from   Mastering Python Scripting for System Administrators Write scripts and automate them for real-world administration tasks using Python

Arrow left icon
Product type Paperback
Published in Jan 2019
Publisher Packt
ISBN-13 9781789133226
Length 318 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Ganesh Sanjiv Naik Ganesh Sanjiv Naik
Author Profile Icon Ganesh Sanjiv Naik
Ganesh Sanjiv Naik
Arrow right icon
View More author details
Toc

Table of Contents (21) Chapters Close

Preface 1. Python Scripting Overview FREE CHAPTER 2. Debugging and Profiling Python Scripts 3. Unit Testing - Introduction to the Unit Testing Framework 4. Automating Regular Administrative Activities 5. Handling Files, Directories, and Data 6. File Archiving, Encrypting, and Decrypting 7. Text Processing and Regular Expressions 8. Documentation and Reporting 9. Working with Various Files 10. Basic Networking - Socket Programming 11. Handling Emails Using Python Scripting 12. Remote Monitoring of Hosts Over Telnet and SSH 13. Building Graphical User Interfaces 14. Working with Apache and Other Log Files 15. SOAP and REST API Communication 16. Web Scraping - Extracting Useful Data from Websites 17. Statistics Gathering and Reporting 18. MySQL and SQLite Database Administrations 19. Assessments 20. Other Books You May Enjoy

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
>>>
You have been reading a chapter from
Mastering Python Scripting for System Administrators
Published in: Jan 2019
Publisher: Packt
ISBN-13: 9781789133226
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image