[Go to site: main page, start]

0% found this document useful (0 votes)
3 views94 pages

Array & String in Python

The document provides a comprehensive guide on Python arrays, detailing their characteristics, methods for declaration, manipulation (such as append, insert, remove), and accessing elements through indexing. It highlights the differences between arrays and lists, explains typecodes, and includes examples for various array operations. Additionally, it covers multidimensional arrays and introduces Object-Oriented Programming in Python.

Uploaded by

hemanath714
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views94 pages

Array & String in Python

The document provides a comprehensive guide on Python arrays, detailing their characteristics, methods for declaration, manipulation (such as append, insert, remove), and accessing elements through indexing. It highlights the differences between arrays and lists, explains typecodes, and includes examples for various array operations. Additionally, it covers multidimensional arrays and introduces Object-Oriented Programming in Python.

Uploaded by

hemanath714
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Array Examples – Declare, Append,

Index, Remove, Count


by HIMANSHU ARORA on AUGUST 14, 2013

An array is a data structure that stores values of same data type. In Python,
this is the main difference between arrays and lists.

While python lists can contain values corresponding to different data types,
arrays in python can only contain values corresponding to same data type. In
this tutorial, we will understand the Python arrays with few examples.

If you are new to Python, get started with the Python Introduction article.
To use arrays in python language, you need to import the standard ‘array’
module. This is because array is not a fundamental data type like strings,
integer etc. Here is how you can import ‘array’ module in python :

from array import *

Once you have imported the ‘array’ module, you can declare an array. Here is
how you do it:

arrayIdentifierName = array(typecode, [Initializers]


In the declaration above, ‘arrayIdentifierName’ is the name of array,
‘typecode’ lets python know the type of array and ‘Initializers’ are the values
with which array is initialized.

my_array = array('i',[1,2,3,4])

In the example above, typecode used is ‘i’. This typecode represents signed
integer whose size is 2 bytes.

Typecodes are the codes that are used to define the type of array values or
the type of array. Here is the list of available typecodes:

 ‘b’ -> Represents signed integer of size 1 byte


 ‘B’ -> Represents unsigned integer of size 1 byte
 ‘c’ -> Represents character of size 1 byte
 ‘u’ -> Represents unicode character of size 2 bytes
 ‘h’ -> Represents signed integer of size 2 bytes
 ‘H’ -> Represents unsigned integer of size 2 bytes
 ‘i’ -> Represents signed integer of size 2 bytes
 ‘I’ -> Represents unsigned integer of size 2 bytes
 ‘w’ -> Represents unicode character of size 4 bytes
 ‘l’ -> Represents signed integer of size 4 bytes
 ‘L’ -> Represents unsigned integer of size 4 bytes
 ‘f’ -> Represents floating point of size 4 bytes
 ‘d’ -> Represents floating point of size 8 bytes
On a related topic, you should also know how to use Python Lists effectively.
1. Basic example
Here is a simple example of an array containing 5 integers

~$ python

Python 2.7.4 (default, Apr 19 2013, 18:28:01)

[GCC 4.7.3] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>> from array import *


>>> my_array = array('i', [1,2,3,4,5])
>>> for i in my_array:
... print(i)
...
1
2
3
4
5

So this way we can create a simple python array and print it.

2. Access individual elements through indexes


Individual elements can be accessed through indexes. Here is an example :
>>> my_array[1]

>>> my_array[2]

>>> my_array[0]

Remember that indexes start from zero.

3. Append any value to the array using append() method


Here is an example :

>>> my_array.append(6)
>>> my_array
array('i', [1, 2, 3, 4, 5, 6])

So we see that the value ‘6’ was appended to the existing array values.

4. Insert value in an array using insert() method


We can use the insert() method to insert a value at any index of the array.
Here is an example :

>>> my_array.insert(0,0)
>>> my_array
array('i', [0, 1, 2, 3, 4, 5, 6])

In the above example, using insert() method, the value 0 was inserted at index
0. Note that the first argument is the index while second argument is the
value.

5. Extend python array using extend() method


A python array can be extended with more than one value using extend()
method. Here is an example :

>>> my_extnd_array = array('i', [7,8,9,10])

>>> my_array.extend(my_extnd_array)
>>> my_array
array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

So we see that the array my_array was extended with values from
my_extnd_array.

6. Add items from list into array using fromlist() method


Here is an example:
>>> c=[11,12,13]

>>> my_array.fromlist(c)
>>> my_array
array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])

So we see that the values 11,12 and 13 were added from list ‘c’ to ‘my_array’.

7. Remove any array element using remove() method


Here is an example :

>>> my_array.remove(13)
>>> my_array
array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

So we see that the element 13 was removed from the array.

8. Remove last array element using pop() method


Here is an example :

>>> my_array.pop()
12
>>> my_array
array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])

So we see that the last element 12 was popped out of array.


9. Fetch any element through its index using index() method
Here is an example :

>>> my_array.index(5)
5

So we see that the value at index 5 was fetched through this method.

10. Reverse a python array using reverse() method


Here is an example :

>>> my_array.reverse()
>>> my_array
array('i', [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0])

So we see that the complete array got reversed.

11. Get array buffer information through buffer_info() method


This method provides you the array buffer start address in memory and
number of elements in array. Here is an example:

>>> my_array.buffer_info()
(33881712, 12)
So we see that buffer start address and number of elements were provided in
output.

12. Check for number of occurrences of an element using count()


method
Here is an example :

>>> my_array.count(11)
1

So we see that the element 11 occurred only once in the array.

13. Convert array to string using tostring() method


Here is an example :

>>> my_char_array = array('c', ['g','e','e','k'])

>>> my_char_array

array('c', 'geek')

>>> my_char_array.tostring()
'geek'

So we see that the character array was converted to string using this method.
14. Convert array to a python list with same elements using tolist()
method
Here is an example :

>>> c = my_array.tolist()
>>> c
[11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

So we see that list ‘c’ was created by using tolist() method on my_array.

15. Append a string to char array using fromstring() method


Here is an example :

>>> my_char_array.fromstring("stuff")
>>> my_char_array
array('c', 'geekstuff')

So we see that the string “stuff” was added to my_char_array.

Create an Array
We can create a Python array with comma separated elements between square
brackets[].
Example 1: How to create an array in Python?
We can make an integer array and store it to arr.

arr = [10, 20, 30, 40, 50]

Access elements of an Array


We can access individual elements of an array using index inside square brackets [].

Array Index
Index is the position of element in an array. In Python, arrays are zero-indexed. This
means, the element's position starts with 0 instead of 1.

Example 2: Accessing elements of array using indexing


arr = [10, 20, 30, 40, 50]
print(arr[0])

print(arr[1])

print(arr[2])

When we run the above program, the output will be:


10

20

30

Here, the first element of arr is arr[0], second is arr[1], third is arr[2], and so on.

Negative Indexing
Python programming supports negative indexing of arrays, something that is not available
in arrays in most programming languages. This means the index value of -1 gives the last
element, and -2 gives the second to last element of an array.

Example 3: Accessing elements of array using negative indexing


arr = [10, 20, 30, 40, 50]
print(arr[-1])

print(arr[-2])

When we run the above program, the output will be:

50
40

Find length of an Array


Python arrays are just lists, so finding the length of an array is equivalent to finding length
of a list in Python.

Example 4: Find length of an array using len()


brands = ["Coke", "Apple", "Google", "Microsoft", "Toyota"]
num_brands = len(brands)
print(num_brands)

When we run the above program, the output will be:

As seen from the above example, the len function gives the length of array brands which
is 5.
Add an element to an Array
To add a new element to an array, we use append() method in Python.

Example 5: Adding an element in an array using append()


add = ['a', 'b', 'c']
[Link]('d')
print(add)

When we run the above program,the output will be

['a', 'b', 'c', 'd']

Here, we used append() method to add 'd'.

Remove elements from an Array


Python's list implementation of array allows us to delete any elements from an array
using del operator.

Similarly, we can also use remove() and pop() methods to remove elements in an array.
Example 6: Removing elements of an array using del, remove()
and pop()
colors = ["violet", "indigo", "blue", "green", "yellow", "orange",
"red"]
del color[4]
[Link]("blue")
[Link](3)
print(color)

When we run the above program, the output will be

['violet', 'indigo', 'green', 'red']

In the above program,

 First, we used del statement to remove element located at index 4, i.e. 'yellow'.
Now, the colors array becomes ['violet', 'indigo', 'blue', 'green', 'orange', 'red'].
 Then, we used remove('blue') function to remove element 'blue' from the array.
Now the colors array becomes ['violet', 'indigo', 'green', 'orange', 'red'].
 Then, we used pop(3) function to delete element at index 3, i.e. 'orange'. Finally,
the colors array becomes ['violet', 'indigo', 'orange', 'red'] as shown in the output.
Modify elements of an Array
We can change values of elements within an array using indexing and assignment
operator (=). We select the position of any element using indexing and use assignment
operator to provide a new value for the element.

Example 7: Modifying elements of an array using Indexing


fruits = ["Apple", "Banana", "Mango", "Grapes", "Orange"]
fruits[1] = "Pineapple"
fruits[-1] = "Guava"
print(fruits)

When we run the above program, the output will be:

['Apple', 'Pineapple', 'Mango', 'Grapes', 'Guava']

When we print the elements of fruits it shows that Pineapple have replaced Mango at
index 1.

We also changed last element of fruits to Guava, using negative indexing.

Thus, we can change and update the elements of array easily.


Python operators to modify elements in an Array
In Python arrays, operators like +, * can also be used to modify elements.

We can use + operator to concatenate (combine) two arrays.

Example 8: Concatenating two arrays using + operator


concat = [1, 2, 3]
concat + [4,5,6]
print(concat)

When we run the above program. the output will be:

[1, 2, 3, 4, 5, 6]

Similarly, we can use * operator to repeat the elements multiple times.

Example 8: Repeating elements in array using * operator


repeat = ["a"]
repeat = repeat * 5
print(repeat)

When we run the above program, the output will be

['a', 'a', 'a', 'a', 'a']

We repeated string "a" for 5 times, using * operator.

Slicing an Array
Python has a slicing feature which allows to access pieces of an array. We, basically, slice
an array using a given range (eg. 2nd to 5th position), giving us elements we require. This
is done by using indexes separated by a colon [x : y].

We can use negative indexing with slicing too.

Example 9: Slicing an array using Indexing


fruits = ["Apple", "Banana", "Mango", "Grapes", "Orange"]
print(fruits[1:4])
print(fruits[ : 3])
print(fruits[-4:])
print(fruits[-3:-1])

When we run the above program, the output will be:

['Banana', 'Mango', 'Grapes']

['Apple', 'Banana', 'Mango']

['Banana', 'Mango', 'Grapes', 'Orange']

['Mango', 'Grapes']

While creating a slice [1:4], slicing starts (inclusive) with left index number, and slicing
ends (exclusive) with right index number. This means slicing only prints out the elements
of position 1, 2, and 3. Here, position 4 is exclusive so we don't get Orange as an output.

In the code fruits[:3], you can see we didn't include the index on the left. This means,
slicing takes all elements until the index on the right (excluding the right index), i.e. first 3
(0, 1, 2) elements of the array.

Likewise, fruits[-4:] prints all elements after second position (1 or -4) i.e 'Banana'. This
code is equivalent to fruits[1:].

In the final code, fruits[-3:-1], it all elements starting from index -3 to -2.
Python Array Methods
Other array operations are also available in Python using list/array methods given as:

Methods Functions

append() to add element to the end of the list

extend() to extend all elements of a list to the another list

insert() to insert an element at the another index

remove() to remove an element from the list

pop() to remove elements return element at the given index

clear() to remove all elements from the list


index() to return the index of the first matched element

count() to count of number of elements passed as an argument

sort() to sort the elements in ascending order by default

reverse() to reverse order element in a list

copy() to return a copy of elements in a list

Multidimensional arrays
All arrays created above are single dimensional. We can also create a multidimensional
array in Python. A multidimensional array is an array within an array. This means an array
holds different arrays inside it.

Example 10: Create a two-dimensional array using lists


multd = [[1,2], [3,4], [5,6], [7,8]]
print(multd[0])
print(multd[3])
print(multd[2][1])
print(multd[3][0])

When we run the above program, the output will be

[1, 2]

[7, 8]

Here, we have 4 elements and each elements hold another 2 sub-elements.

Introduction to OOPs in Python


Python is a multi-paradigm programming language. Meaning, it supports different
programming approach.
One of the popular approach to solve a programming problem is by creating objects. This
is known as Object-Oriented Programming (OOP).

An object has two characteristics:

 attributes
 behavior

Let's take an example:

Parrot is an object,

 name, age, color are attributes


 singing, dancing are behavior

The concept of OOP in Python focuses on creating reusable code. This concept is also
known as DRY (Don't Repeat Yourself).

In Python, the concept of OOP follows some basic principles:

A process of using details from a new class without modifying existing


Inheritance
class.

Encapsulation Hiding the private details of a class from other objects.

Polymorphism A concept of using common operation in different ways for different data
input.

Class
A class is a blueprint for the object.

We can think of class as an sketch of a parrot with labels. It contains all the details about
the name, colors, size etc. Based on these descriptions, we can study about the parrot.
Here, parrot is an object.

The example for class of parrot can be :

class Parrot:

pass

Here, we use class keyword to define an empty class Parrot. From class, we construct
instances. An instance is a specific object created from a particular class.
Object
An object (instance) is an instantiation of a class. When class is defined, only the
description for the object is defined. Therefore, no memory or storage is allocated.

The example for object of parrot class can be:

obj = Parrot()

Here, obj is object of class Parrot.

Suppose we have details of parrot. Now, we are going to show how to build the class and
objects of parrot.

Example 1: Creating Class and Object in Python


class Parrot:

# class attribute

species = "bird"

# instance attribute

def __init__(self, name, age):

[Link] = name

[Link] = age
# instantiate the Parrot class

blu = Parrot("Blu", 10)

woo = Parrot("Woo", 15)

# access the class attributes

print("Blu is a {}".format(blu.__class__.species))

print("Woo is also a {}".format(woo.__class__.species))

# access the instance attributes

print("{} is {} years old".format( [Link], [Link]))

print("{} is {} years old".format( [Link], [Link]))

Run
Powered by DataCamp

When we run the program, the output will be:

Blu is a bird

Woo is also a bird

Blu is 10 years old


Woo is 15 years old

In the above program, we create a class with name Parrot. Then, we define attributes.
The attributes are a characteristic of an object.

Then, we create instances of the Parrot class. Here, blu and woo are references (value)
to our new objects.

Then, we access the class attribute using __class __.species. Class attributes are same
for all instances of a class. Similarly, we access the instance attributes
using [Link] and [Link]. However, instance attributes are different for every instance
of a class.

To learn more about classes and objects, go to Python Classes and Objects

Methods
Methods are functions defined inside the body of a class. They are used to define the
behaviors of an object.

Example 2 : Creating Methods in Python


class Parrot:
# instance attributes

def __init__(self, name, age):

[Link] = name

[Link] = age

# instance method

def sing(self, song):

return "{} sings {}".format([Link], song)

def dance(self):

return "{} is now dancing".format([Link])

# instantiate the object

blu = Parrot("Blu", 10)

# call our instance methods

print([Link]("'Happy'"))

print([Link]())

Run
Powered by DataCamp

When we run program, the output will be:


Blu sings 'Happy'

Blu is now dancing

In the above program, we define two methods i.e sing() and dance(). These are called
instance method because they are called on an instance object i.e blu.

Inheritance
Inheritance is a way of creating new class for using details of existing class without
modifying it. The newly formed class is a derived class (or child class). Similarly, the
existing class is a base class (or parent class).

Example 3: Use of Inheritance in Python


# parent class

class Bird:

def __init__(self):

print("Bird is ready")

def whoisThis(self):
print("Bird")

def swim(self):

print("Swim faster")

# child class

class Penguin(Bird):

def __init__(self):

# call super() function

super().__init__()

print("Penguin is ready")

def whoisThis(self):

print("Penguin")

def run(self):

print("Run faster")

peggy = Penguin()

[Link]()

[Link]()

[Link]()

Run
Powered by DataCamp
When we run this program, the output will be:

Bird is ready

Penguin is ready

Penguin

Swim faster

Run faster

In the above program, we created two classes i.e. Bird (parent class) and Penguin (child
class). The child class inherits the functions of parent class. We can see this
from swim()method. Again, the child class modified the behavior of parent class. We can
see this from whoisThis() method. Furthermore, we extend the functions of parent class,
by creating a new run() method.

Additionally, we use super() function before __init__() method. This is because we


want to pull the content of __init__() method from the parent class into the child class.
Encapsulation
Using OOP in Python, we can restrict access to methods and variables. This prevent data
from direct modification which is called encapsulation. In Python, we denote private
attribute using underscore as prefix i.e single “ _ “ or double “ __“.

Example 4: Data Encapsulation in Python


class Computer:

def __init__(self):

self.__maxprice = 900

def sell(self):

print("Selling Price: {}".format(self.__maxprice))

def setMaxPrice(self, price):

self.__maxprice = price

c = Computer()

[Link]()

# change the price

c.__maxprice = 1000

[Link]()

# using setter function

[Link](1000)
[Link]()

Run
Powered by DataCamp

When we run this program, the output will be:

Selling Price: 900

Selling Price: 900

Selling Price: 1000

In the above program, we defined a class Computer. We use __init__() method to store
the maximum selling price of computer. We tried to modify the price. However, we can’t
change it because Python treats the __maxprice as private attributes. To change the
value, we used a setter function i.e setMaxPrice() which takes price as parameter.

Polymorphism
Polymorphism is an ability (in OOP) to use common interface for multiple form (data
types).
Suppose, we need to color a shape, there are multiple shape option (rectangle, square,
circle). However we could use same method to color any shape. This concept is called
Polymorphism.

Example 5: Using Polymorphism in Python


class Parrot:

def fly(self):

print("Parrot can fly")

def swim(self):

print("Parrot can't swim")

class Penguin:

def fly(self):

print("Penguin can't fly")

def swim(self):

print("Penguin can swim")

# common interface

def flying_test(bird):

[Link]()

#instantiate objects
blu = Parrot()

peggy = Penguin()

# passing the object

flying_test(blu)

flying_test(peggy)

Run
Powered by DataCamp

When we run above program, the output will be:

Parrot can fly

Penguin can't fly

In the above program, we defined two classes Parrot and Penguin. Each of them have
common method fly() method. However, their functions are different. To allow
polymorphism, we created common interface i.e flying_test() function that can take any
object. Then, we passed the objects blu and peggy in the flying_test() function, it ran
effectively.
Key Points to Remember:
 The programming gets easy and efficient.
 The class is sharable, so codes can be reused.
 The productivity of programmars increases
 Data is safe and secure with data abstraction.

What are classes and objects in Python?


Python is an object oriented programming language. Unlike procedure oriented
programming, where the main emphasis is on functions, object oriented programming
stress on objects.

Object is simply a collection of data (variables) and methods (functions) that act on those
data. And, class is a blueprint for the object.

We can think of class as a sketch (prototype) of a house. It contains all the details about
the floors, doors, windows etc. Based on these descriptions we build the house. House is
the object.

As, many houses can be made from a description, we can create many objects from a
class. An object is also called an instance of a class and the process of creating this
object is called instantiation.
Defining a Class in Python
Like function definitions begin with the keyword def, in Python, we define a class using the
keyword class.

The first string is called docstring and has a brief description about the class. Although not
mandatory, this is recommended.

Here is a simple class definition.

class MyNewClass:
'''This is a docstring. I have created a new class'''
pass

A class creates a new local namespace where all its attributes are defined. Attributes may
be data or functions.

There are also special attributes in it that begins with double underscores (__). For
example, __doc__ gives us the docstring of that class.

As soon as we define a class, a new class object is created with the same name. This
class object allows us to access the different attributes as well as to instantiate new
objects of that class.

class MyClass:

"This is my second class"


a = 10

def func(self):

print('Hello')

# Output: 10

print(MyClass.a)

# Output: <function [Link] at 0x0000000003079BF8>

print([Link])

# Output: 'This is my second class'

print(MyClass.__doc__)

Run
Powered by DataCamp

When you run the program, the output will be:

10

<function 0x7feaa932eae8="" at="" [Link]="">

This is my second class


Creating an Object in Python
We saw that the class object could be used to access different attributes.

It can also be used to create new object instances (instantiation) of that class. The
procedure to create an object is similar to a function call.

>>> ob = MyClass()

This will create a new instance object named ob. We can access attributes of objects
using the object name prefix.

Attributes may be data or method. Method of an object are corresponding functions of that
class. Any function object that is a class attribute defines a method for objects of that
class.

This means to say, since [Link] is a function object (attribute of


class), [Link] will be a method object.

class MyClass:

"This is my second class"

a = 10

def func(self):

print('Hello')
# create a new MyClass

ob = MyClass()

# Output: <function [Link] at 0x000000000335B0D0>

print([Link])

# Output: <bound method [Link] of <__main__.MyClass object at


0x000000000332DEF0>>

print([Link])

# Calling function func()

# Output: Hello

[Link]()

RunSession Inactive

You may have noticed the self parameter in function definition inside the class but, we
called the method simply as [Link]() without any arguments. It still worked.

This is because, whenever an object calls its method, the object itself is passed as the first
argument. So, [Link]() translates into [Link](ob).

In general, calling a method with a list of n arguments is equivalent to calling the


corresponding function with an argument list that is created by inserting the method's
object before the first argument.

For these reasons, the first argument of the function in class must be the object itself. This
is conventionally called self. It can be named otherwise but we highly recommend to
follow the convention.
Now you must be familiar with class object, instance object, function object, method object
and their differences.

Constructors in Python
Class functions that begins with double underscore (__) are called special functions as
they have special meaning.

Of one particular interest is the __init__() function. This special function gets called
whenever a new object of that class is instantiated.

This type of function is also called constructors in Object Oriented Programming (OOP).
We normally use it to initialize all the variables.

class ComplexNumber:

def __init__(self,r = 0,i = 0):

[Link] = r

[Link] = i

def getData(self):

print("{0}+{1}j".format([Link],[Link]))

# Create a new ComplexNumber object

c1 = ComplexNumber(2,3)
# Call getData() function

# Output: 2+3j

[Link]()

# Create another ComplexNumber object

# and create a new attribute 'attr'

c2 = ComplexNumber(5)

[Link] = 10

# Output: (5, 0, 10)

print(([Link], [Link], [Link]))

# but c1 object doesn't have attribute 'attr'

# AttributeError: 'ComplexNumber' object has no attribute 'attr'

[Link]

Run

In the above example, we define a new class to represent complex numbers. It has two
functions, __init__() to initialize the variables (defaults to zero) and getData() to display
the number properly.

An interesting thing to note in the above step is that attributes of an object can be created
on the fly. We created a new attribute attr for object c2 and we read it as well. But this did
not create that attribute for object c1.
Deleting Attributes and Objects
Any attribute of an object can be deleted anytime, using the del statement. Try the
following on the Python shell to see the output.

>>> c1 = ComplexNumber(2,3)
>>> del [Link]
>>> [Link]()
Traceback (most recent call last):
...
AttributeError: 'ComplexNumber' object has no attribute 'imag'

>>> del [Link]


>>> [Link]()
Traceback (most recent call last):
...
AttributeError: 'ComplexNumber' object has no attribute 'getData'

We can even delete the object itself, using the del statement.

>>> c1 = ComplexNumber(1,3)
>>> del c1
>>> c1
Traceback (most recent call last):
...
NameError: name 'c1' is not defined

Actually, it is more complicated than that. When we do c1 = ComplexNumber(1,3), a new


instance object is created in memory and the name c1 binds with it.

On the command del c1, this binding is removed and the name c1 is deleted from the
corresponding namespace. The object however continues to exist in memory and if no
other name is bound to it, it is later automatically destroyed.

This automatic destruction of unreferenced objects in Python is also called garbage


collection.
What is Inheritance?
Inheritance is a powerful feature in object oriented programming.

It refers to defining a new class with little or no modification to an existing class. The new
class is called derived (or child) class and the one from which it inherits is called the base
(or parent) class.

Python Inheritance Syntax


class BaseClass:

Body of base class

class DerivedClass(BaseClass):

Body of derived class

Derived class inherits features from the base class, adding new features to it. This results
into re-usability of code.
Example of Inheritance in Python
To demonstrate the use of inheritance, let us take an example.

A polygon is a closed figure with 3 or more sides. Say, we have a class


called Polygondefined as follows.

class Polygon:
def __init__(self, no_of_sides):

self.n = no_of_sides

[Link] = [0 for i in range(no_of_sides)]

def inputSides(self):

[Link] = [float(input("Enter side "+str(i+1)+" : ")) for i in


range(self.n)]

def dispSides(self):

for i in range(self.n):

print("Side",i+1,"is",[Link][i])

This class has data attributes to store the number of sides, n and magnitude of each side
as a list, sides.
Method inputSides() takes in magnitude of each side and similarly, dispSides() will
display these properly.

A triangle is a polygon with 3 sides. So, we can created a class called Triangle which
inherits from Polygon. This makes all the attributes available in class Polygon readily
available in Triangle. We don't need to define them again (code re-usability). Triangle is
defined as follows.

class Triangle(Polygon):
def __init__(self):
Polygon.__init__(self,3)

def findArea(self):
a, b, c = [Link]
# calculate the semi-perimeter
s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

However, class Triangle has a new method findArea() to find and print the area of the
triangle. Here is a sample run.

>>> t = Triangle()
>>> [Link]()
Enter side 1 : 3
Enter side 2 : 5
Enter side 3 : 4

>>> [Link]()
Side 1 is 3.0
Side 2 is 5.0
Side 3 is 4.0

>>> [Link]()
The area of the triangle is 6.00

We can see that, even though we did not define methods


like inputSides() or dispSides()for class Triangle, we were able to use them.

If an attribute is not found in the class, search continues to the base class. This repeats
recursively, if the base class is itself derived from other classes.
Method Overriding in Python
In the above example, notice that __init__() method was defined in both
classes, Triangleas well Polygon. When this happens, the method in the derived class
overrides that in the base class. This is to say, __init__() in Triangle gets preference
over the same in Polygon.

Generally when overriding a base method, we tend to extend the definition rather than
simply replace it. The same is being done by calling the method in base class from the
one in derived class (calling Polygon.__init__() from __init__() in Triangle).

A better option would be to use the built-in function super(). So, super().__init__(3) is
equivalent to Polygon.__init__(self,3) and is preferred. You can learn more about
the super() function in Python.

Two built-in functions isinstance() and issubclass() are used to check inheritances.
Function isinstance() returns True if the object is an instance of the class or other
classes derived from it. Each and every class in Python inherits from the base
class object.

>>> isinstance(t,Triangle)
True

>>> isinstance(t,Polygon)
True
>>> isinstance(t,int)
False

>>> isinstance(t,object)
True

Similarly, issubclass() is used to check for class inheritance.

>>> issubclass(Polygon,Triangle)
False

>>> issubclass(Triangle,Polygon)
True

>>> issubclass(bool,int)
True

Multiple Inheritance in Python


Like C++, a class can be derived from more than one base classes in Python. This is
called multiple inheritance.
In multiple inheritance, the features of all the base classes are inherited into the derived
class. The syntax for multiple inheritance is similar to single inheritance.

Example
class Base1:
pass

class Base2:
pass

class MultiDerived(Base1, Base2):


pass

Here, MultiDerived is derived from classes Base1 and Base2.


The class MultiDerived inherits from both Base1 and Base2.

Multilevel Inheritance in Python


On the other hand, we can also inherit form a derived class. This is called multilevel
inheritance. It can be of any depth in Python.

In multilevel inheritance, features of the base class and the derived class is inherited into
the new derived class.

An example with corresponding visualization is given below.


class Base:
pass

class Derived1(Base):
pass

class Derived2(Derived1):
pass

4. Object Oriented Programming


4.1. State
Suppose we want to model a bank account with support
for deposit and withdraw operations. One way to do that is by using global state as
shown in the following example.

balance = 0

def deposit(amount):
global balance
balance += amount
return balance
def withdraw(amount):
global balance
balance -= amount
return balance
The above example is good enough only if we want to have just a single account. Things
start getting complicated if want to model multiple accounts.

We can solve the problem by making the state local, probably by using a dictionary to
store the state.

def make_account():
return {'balance': 0}

def deposit(account, amount):


account['balance'] += amount
return account['balance']

def withdraw(account, amount):


account['balance'] -= amount
return account['balance']
With this it is possible to work with multiple accounts at the same time.

>>> a = make_account()
>>> b = make_account()
>>> deposit(a, 100)
100
>>> deposit(b, 50)
50
>>> withdraw(b, 10)
40
>>> withdraw(a, 10)
90
4.2. Classes and Objects
class BankAccount:
def __init__(self):
[Link] = 0

def withdraw(self, amount):


[Link] -= amount
return [Link]

def deposit(self, amount):


[Link] += amount
return [Link]

>>> a = BankAccount()
>>> b = BankAccount()
>>> [Link](100)
100
>>> [Link](50)
50
>>> [Link](10)
40
>>> [Link](10)
90

4.3. Inheritance
Let us try to create a little more sophisticated account type where the account holder has
to maintain a pre-determined minimum balance.

class MinimumBalanceAccount(BankAccount):
def __init__(self, minimum_balance):
BankAccount.__init__(self)
self.minimum_balance = minimum_balance

def withdraw(self, amount):


if [Link] - amount < self.minimum_balance:
print 'Sorry, minimum balance must be maintained.'
else:
[Link](self, amount)
Problem 1: What will the output of the following program.

class A:
def f(self):
return self.g()

def g(self):
return 'A'

class B(A):
def g(self):
return 'B'

a = A()
b = B()
print a.f(), b.f()
print a.g(), b.g()
Example: Drawing Shapes

class Canvas:
def __init__(self, width, height):
[Link] = width
[Link] = height
[Link] = [[' '] * width for i in range(height)]

def setpixel(self, row, col):


[Link][row][col] = '*'

def getpixel(self, row, col):


return [Link][row][col]
def display(self):
print "\n".join(["".join(row) for row in [Link]])

class Shape:
def paint(self, canvas): pass

class Rectangle(Shape):
def __init__(self, x, y, w, h):
self.x = x
self.y = y
self.w = w
self.h = h

def hline(self, x, y, w):


pass

def vline(self, x, y, h):


pass

def paint(self, canvas):


hline(self.x, self.y, self.w)
hline(self.x, self.y + self.h, self.w)
vline(self.x, self.y, self.h)
vline(self.x + self.w, self.y, self.h)

class Square(Rectangle):
def __init__(self, x, y, size):
Rectangle.__init__(self, x, y, size, size)

class CompoundShape(Shape):
def __init__(self, shapes):
[Link] = shapes

def paint(self, canvas):


for s in [Link]:
[Link](canvas)
4.4. Special Class Methods
In Python, a class can implement certain operations that are invoked by special syntax
(such as arithmetic operations or subscripting and slicing) by defining methods with
special names. This is Python’s approach to operator overloading, allowing classes to
define their own behavior with respect to language operators.

For example, the + operator invokes __add__ method.

>>> a, b = 1, 2
>>> a + b
3
>>> a.__add__(b)
3
Just like __add__ is called for + operator, __sub__ , __mul__ and __div__ methods are
called for -, *, and / operators.

Example: Rational Numbers

Suppose we want to do arithmetic with rational numbers. We want to be able to add,


subtract, multiply, and divide them and to test whether two rational numbers are equal.

We can add, subtract, multiply, divide, and test equality by using the following relations:

n1/d1 + n2/d2 = (n1*d2 + n2*d1)/(d1*d2)


n1/d1 - n2/d2 = (n1*d2 - n2*d1)/(d1*d2)
n1/d1 * n2/d2 = (n1*n2)/(d1*d2)
(n1/d1) / (n2/d2) = (n1*d2)/(d1*n2)

n1/d1 == n2/d2 if and only if n1*d2 == n2*d1


Lets write the rational number class.

class RationalNumber:
"""
Rational Numbers with support for arthmetic operations.

>>> a = RationalNumber(1, 2)
>>> b = RationalNumber(1, 3)
>>> a + b
5/6
>>> a - b
1/6
>>> a * b
1/6
>>> a/b
3/2
"""
def __init__(self, numerator, denominator=1):
self.n = numerator
self.d = denominator

def __add__(self, other):


if not isinstance(other, RationalNumber):
other = RationalNumber(other)

n = self.n * other.d + self.d * other.n


d = self.d * other.d
return RationalNumber(n, d)

def __sub__(self, other):


if not isinstance(other, RationalNumber):
other = RationalNumber(other)
n1, d1 = self.n, self.d
n2, d2 = other.n, other.d
return RationalNumber(n1*d2 - n2*d1, d1*d2)

def __mul__(self, other):


if not isinstance(other, RationalNumber):
other = RationalNumber(other)

n1, d1 = self.n, self.d


n2, d2 = other.n, other.d
return RationalNumber(n1*n2, d1*d2)

def __div__(self, other):


if not isinstance(other, RationalNumber):
other = RationalNumber(other)

n1, d1 = self.n, self.d


n2, d2 = other.n, other.d
return RationalNumber(n1*d2, d1*n2)

def __str__(self):
return "%s/%s" % (self.n, self.d)

__repr__ = __str__

4.5. Errors and Exceptions


We’ve already seen exceptions in various places. Python gives NameError when we try to
use a variable that is not defined.

>>> foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
try adding a string to an integer:
>>> "foo" + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
try dividing a number by 0:

>>> 2/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
or, try opening a file that is not there:

>>> open("[Link]")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: '[Link]'
Python raises exception in case errors. We can write programs to handle such errors. We
too can raise exceptions when an error case in encountered.

Exceptions are handled by using the try-except statements.

def main():
filename = [Link][1]
try:
for row in parse_csv(filename):
print row
except IOError:
print >> [Link], "The given file doesn't exist: ", filename
[Link](1)
This above example prints an error message and exits with an error status when an
IOError is encountered.

The except statement can be written in multiple ways:

# catch all exceptions


try:
...
except:

# catch just one exception


try:
...
except IOError:
...

# catch one exception, but provide the exception object


try:
...
except IOError, e:
...

# catch more than one exception


try:
...
except (IOError, ValueError), e:
...
It is possible to have more than one except statements with one try.

try:
...
except IOError, e:
print >> [Link], "Unable to open the file (%s): %s" % (str(e), filename)
[Link](1)
except FormatError, e:
print >> [Link], "File is badly formatted (%s): %s" % (str(e), filename)
The try statement can have an optional else clause, which is executed only if no exception
is raised in the try-block.

try:
...
except IOError, e:
print >> [Link], "Unable to open the file (%s): %s" % (str(e), filename)
[Link](1)
else:
print "successfully opened the file", filename
There can be an optional else clause with a try statement, which is executed irrespective
of whether or not exception has occured.

try:
...
except IOError, e:
print >> [Link], "Unable to open the file (%s): %s" % (str(e), filename)
[Link](1)
finally:
delete_temp_files()
Exception is raised using the raised keyword.

raise Exception("error message")


All the exceptions are extended from the built-in Exception class.

class ParseError(Exception):
pass

Problem 2: What will be the output of the following program?

try:
print "a"
except:
print "b"
else:
print "c"
finally:
print "d"
Problem 3: What will be the output of the following program?

try:
print "a"
raise Exception("doom")
except:
print "b"
else:
print "c"
finally:
print "d"
Problem 4: What will be the output of the following program?

def f():
try:
print "a"
return
except:
print "b"
else:
print "c"
finally:
print "d"

f()

5. Iterators & Generators


5.1. Iterators
We use for statement for looping over a list.

>>> for i in [1, 2, 3, 4]:


... print i,
...
1
2
3
4
If we use it with a string, it loops over its characters.

>>> for c in "python":


... print c
...
p
y
t
h
o
n
If we use it with a dictionary, it loops over its keys.

>>> for k in {"x": 1, "y": 2}:


... print k
...
y
x
If we use it with a file, it loops over lines of the file.

>>> for line in open("[Link]"):


... print line,
...
first line
second line
So there are many types of objects which can be used with a for loop. These are called
iterable objects.

There are many functions which consume these iterables.

>>> ",".join(["a", "b", "c"])


'a,b,c'
>>> ",".join({"x": 1, "y": 2})
'y,x'
>>> list("python")
['p', 'y', 't', 'h', 'o', 'n']
>>> list({"x": 1, "y": 2})
['y', 'x']
5.1.1. The Iteration Protocol
The built-in function iter takes an iterable object and returns an iterator.

>>> x = iter([1, 2, 3])


>>> x
<listiterator object at 0x1004ca850>
>>> [Link]()
1
>>> [Link]()
2
>>> [Link]()
3
>>> [Link]()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Each time we call the next method on the iterator gives us the next element. If there are
no more elements, it raises a StopIteration.

Iterators are implemented as classes. Here is an iterator that works like built-
in xrange function.

class yrange:
def __init__(self, n):
self.i = 0
self.n = n

def __iter__(self):
return self

def next(self):
if self.i < self.n:
i = self.i
self.i += 1
return i
else:
raise StopIteration()
The __iter__ method is what makes an object iterable. Behind the scenes,
the iter function calls __iter__ method on the given object.
The return value of __iter__ is an iterator. It should have a next method and
raise StopIteration when there are no more elements.

Lets try it out:

>>> y = yrange(3)
>>> [Link]()
0
>>> [Link]()
1
>>> [Link]()
2
>>> [Link]()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 14, in next
StopIteration
Many built-in functions accept iterators as arguments.

>>> list(yrange(5))
[0, 1, 2, 3, 4]
>>> sum(yrange(5))
10
In the above case, both the iterable and iterator are the same object. Notice that
the __iter__ method returned self . It need not be the case always.

class zrange:
def __init__(self, n):
self.n = n

def __iter__(self):
return zrange_iter(self.n)

class zrange_iter:
def __init__(self, n):
self.i = 0
self.n = n

def __iter__(self):
# Iterators are iterables too.
# Adding this functions to make them so.
return self

def next(self):
if self.i < self.n:
i = self.i
self.i += 1
return i
else:
raise StopIteration()
If both iteratable and iterator are the same object, it is consumed in a single iteration.

>>> y = yrange(5)
>>> list(y)
[0, 1, 2, 3, 4]
>>> list(y)
[]
>>> z = zrange(5)
>>> list(z)
[0, 1, 2, 3, 4]
>>> list(z)
[0, 1, 2, 3, 4]
Problem 1: Write an iterator class reverse_iter , that takes a list and iterates it from the
reverse direction. ::
>>> it = reverse_iter([1, 2, 3, 4])
>>> [Link]()
4
>>> [Link]()
3
>>> [Link]()
2
>>> [Link]()
1
>>> [Link]()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

5.2. Generators
Generators simplifies creation of iterators. A generator is a function that produces a
sequence of results instead of a single value.

def yrange(n):
i = 0
while i < n:
yield i
i += 1
Each time the yield statement is executed the function generates a new value.

>>> y = yrange(3)
>>> y
<generator object yrange at 0x401f30>
>>> [Link]()
0
>>> [Link]()
1
>>> [Link]()
2
>>> [Link]()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
So a generator is also an iterator. You don’t have to worry about the iterator protocol.

The word “generator” is confusingly used to mean both the function that generates and
what it generates. In this chapter, I’ll use the word “generator” to mean the genearted
object and “generator function” to mean the function that generates it.

Can you think about how it is working internally?

When a generator function is called, it returns a generator object without even beginning
execution of the function. When next method is called for the first time, the function starts
executing until it reaches yield statement. The yielded value is returned by the next call.

The following example demonstrates the interplay between yield and call
to next method on generator object.

>>> def foo():


... print "begin"
... for i in range(3):
... print "before yield", i
... yield i
... print "after yield", i
... print "end"
...
>>> f = foo()
>>> [Link]()
begin
before yield 0
0
>>> [Link]()
after yield 0
before yield 1
1
>>> [Link]()
after yield 1
before yield 2
2
>>> [Link]()
after yield 2
end
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
Lets see an example:

def integers():
"""Infinite sequence of integers."""
i = 1
while True:
yield i
i = i + 1

def squares():
for i in integers():
yield i * i

def take(n, seq):


"""Returns first n values from the given sequence."""
seq = iter(seq)
result = []
try:
for i in range(n):
[Link]([Link]())
except StopIteration:
pass
return result

print take(5, squares()) # prints [1, 4, 9, 16, 25]

5.3. Generator Expressions


Generator Expressions are generator version of list comprehensions. They look like list
comprehensions, but returns a generator back instead of a list.

>>> a = (x*x for x in range(10))


>>> a
<generator object <genexpr> at 0x401f08>
>>> sum(a)
285
We can use the generator expressions as arguments to various functions that consume
iterators.

>>> sum((x*x for x in range(10)))


285
When there is only one argument to the calling function, the parenthesis around generator
expression can be omitted.

>>> sum(x*x for x in range(10))


285
Another fun example:
Lets say we want to find first 10 (or any n) pythogorian triplets. A triplet (x, y, z) is called
pythogorian triplet if x*x + y*y == z*z .

It is easy to solve this problem if we know till what value of z to test for. But we want to find
first n pythogorian triplets.

>>> pyt = ((x, y, z) for z in integers() for y in xrange(1, z) for x in range(1, y)


if x*x + y*y == z*z)
>>> take(10, pyt)
[(3, 4, 5), (6, 8, 10), (5, 12, 13), (9, 12, 15), (8, 15, 17), (12, 16, 20), (15, 20,
25), (7, 24, 25), (10, 24, 26), (20, 21, 29)]
5.3.1. Example: Reading multiple files

Lets say we want to write a program that takes a list of filenames as arguments and prints
contents of all those files, like cat command in unix.

The traditional way to implement it is:

def cat(filenames):
for f in filenames:
for line in open(f):
print line,
Now, lets say we want to print only the line which has a particular substring,
like grep command in unix.

def grep(pattern, filenames):


for f in filenames:
for line in open(f):
if pattern in line:
print line,
Both these programs have lot of code in common. It is hard to move the common part to a
function. But with generators makes it possible to do it.

def readfiles(filenames):
for f in filenames:
for line in open(f):
yield line

def grep(pattern, lines):


return (line for line in lines if pattern in line)

def printlines(lines):
for line in lines:
print line,

def main(pattern, filenames):


lines = readfiles(filenames)
lines = grep(pattern, lines)
printlines(lines)
The code is much simpler now with each function doing one small thing. We can move all
these functions into a separate module and reuse it in other programs.

Problem 2: Write a program that takes one or more filenames as arguments and prints all
the lines which are longer than 40 characters.

Problem 3: Write a function findfiles that recursively descends the directory tree for the
specified directory and generates paths of all the files in the tree.
Problem 4: Write a function to compute the number of python files (.py extension) in a
specified directory recursively.

Problem 5: Write a function to compute the total number of lines of code in all python files
in the specified directory recursively.

Problem 6: Write a function to compute the total number of lines of code, ignoring empty
and comment lines, in all python files in the specified directory recursively.

Problem 7: Write a program [Link] , that takes an integer n and a filename as


command line arguments and splits the file into multiple small files with each
having n lines.

5.4. Itertools
The itertools module in the standard library provides lot of intersting tools to work with
iterators.

Lets look at some of the interesting functions.

chain – chains multiple iterators together.

>>> it1 = iter([1, 2, 3])


>>> it2 = iter([4, 5, 6])
>>> [Link](it1, it2)
[1, 2, 3, 4, 5, 6]
izip – iterable version of zip

>>> for x, y in [Link](["a", "b", "c"], [1, 2, 3]):


... print x, y
...
a 1
b 2
c 3
Problem 8: Write a function peep , that takes an iterator as argument and returns the first
element and an equivalant iterator.

>>> it = iter(range(5))
>>> x, it1 = peep(it)
>>> print x, list(it1)
0 [0, 1, 2, 3, 4]
Problem 9: The built-in function enumerate takes an iteratable and returns an iterator over
pairs (index, value) for each value in the source.

>>> list(enumerate(["a", "b", "c"])


[(0, "a"), (1, "b"), (2, "c")]
>>> for i, c in enumerate(["a", "b", "c"]):
... print i, c
...
0 a
1 b
2 c
Write a function my_enumerate that works like enumerate .
PYTHON STRINGS
Strings are the simplest and easy to use in Python.

String pythons are immutable.

We can simply create Python String by enclosing a text in single as well as double quotes. Python treat
both single and double quotes statements same.

Accessing Strings:
o In Python, Strings are stored as individual characters in a contiguous memory location.

o The benefit of using String is that it can be accessed from both the directions in forward and
backward.
o Both forward as well as backward indexing are provided using Strings in Python.

o Forward indexing starts with 0,1,2,3,....

o Backward indexing starts with -1,-2,-3,-4,....

eg:
1. str[0]='P'=str[-6] , str[1]='Y' = str[-5] , str[2] = 'T' = str[-4] , str[3] = 'H' = str[-3]
2. str[4] = 'O' = str[-2] , str[5] = 'N' = str[-1].

Simple program to retrieve String in reverse as well as normal form.

1. name="Rajat"
2. length=len(name)
3. i=0
4. for n in range(-1,(-length-1),-1):
5. print name[i],"\t",name[n]
6. i+=1

Output:

>>>
R t
a a
j j
a a
t R
>>>

Strings Operators
There are basically 3 types of Operators supported by String:

1. Basic Operators.

2. Membership Operators.

3. Relational Operators.

Basic Operators:
There are two types of basic operators in String. They are "+" and "*".

String Concatenation Operator :(+)


The concatenation operator (+) concatenate two Strings and forms a new String.

eg:

>>> "ratan" + "jaiswal"

Output:

'ratanjaiswal'
>>>

Expression Output
'10' + '20' '1020'

"s" + "007" 's007'

'abcd123' + 'xyz4' 'abcd123xyz4'

NOTE: Both the operands passed for concatenation must be of same type, else it will show an error.

Eg:

'abc' + 3
>>>

output:

Traceback (most recent call last):


File "", line 1, in
'abc' + 3
TypeError: cannot concatenate 'str' and 'int' objects
>>>

Replication Operator: (*)


Replication operator uses two parameter for operation. One is the integer value and the other one is the
String.

The Replication operator is used to repeat a string number of times. The string will be repeated the
number of times which is given by the integer value.

Eg:
1. >>> 5*"Vimal"

Output:

'VimalVimalVimalVimalVimal'

Expression Output

"soono"*2 'soonosoono'

3*'1' '111'

'$'*5 '$$$$$'

NOTE: We can use Replication operator in any way i.e., int * string or string * int. Both the parameters passed
cannot be of same type.

Membership Operators
Membership Operators are already discussed in the Operators section. Let see with context of String.

There are two types of Membership operators:

1) in:"in" operator return true if a character or the entire substring is present in the specified string,
otherwise false.
2) not in:"not in" operator return true if a character or entire substring does not exist in the specified
string, otherwise false.

Eg:

1. >>> str1="javatpoint"
2. >>> str2='sssit'
3. >>> str3="seomount"
4. >>> str4='java'
5. >>> st5="it"
6. >>> str6="seo"
7. >>> str4 in str1
8. True
9. >>> str5 in str2
10. >>> st5 in str2
11. True
12. >>> str6 in str3
13. True
14. >>> str4 not in str1
15. False
16. >>> str1 not in str4
17. True

Relational Operators:
All the comparison operators i.e., (<,><=,>=,==,!=,<>) are also applicable to strings. The Strings are
compared based on the ASCII value or Unicode(i.e., dictionary Order).

Eg:
1. >>> "RAJAT"=="RAJAT"
2. True
3. >>> "afsha">='Afsha'
4. True
5. >>> "Z"<>"z"
6. True

Explanation:

The ASCII value of a is 97, b is 98, c is 99 and so on. The ASCII value of A is 65,B is 66,C is 67 and so on.
The comparison between strings are done on the basis on ASCII value.

Slice Notation:
String slice can be defined as substring which is the part of string. Therefore further substring can be
obtained from a string.

There can be many forms to slice a string. As string can be accessed or indexed from both the direction
and hence string can also be sliced from both the direction that is left and right.

Syntax:

1. <string_name>[startIndex:endIndex],
2. <string_name>[:endIndex],
3. <string_name>[startIndex:]

Example:

1. >>> str="Nikhil"
2. >>> str[0:6]
3. 'Nikhil'
4. >>> str[0:3]
5. 'Nik'
6. >>> str[2:5]
7. 'khi'
8. >>> str[:6]
9. 'Nikhil'
10. >>> str[3:]
11. 'hil'

Note: startIndex in String slice is inclusive whereas endIndex is exclusive.

String slice can also be used with Concatenation operator to get whole string.

Eg:

1. >>> str="Mahesh"
2. >>> str[:6]+str[6:]
3. 'Mahesh'

//here 6 is the length of the string.

String Functions and Methods:


There are many predefined or built in functions in String. They are as follows:

capitalize() It capitalizes the first character of the String.

count(string,begin,end) Counts number of times substring occurs in a String


between begin and end index.

endswith(suffix ,begin=0,end= Returns a Boolean value if the string terminates with


n) given suffix between begin and end.

find(substring ,beginIndex, It returns the index value of the string where substring is
endIndex) found between begin index and end index.

index(subsring, beginIndex, Same as find() except it raises an exception if string is


endIndex) not found.

isalnum() It returns True if characters in the string are


alphanumeric i.e., alphabets or numbers and there is at
least 1 character. Otherwise it returns False.

isalpha() It returns True when all the characters are alphabets and
there is at least one character, otherwise False.

isdigit() It returns True if all the characters are digit and there is
at least one character, otherwise False.

islower() It returns True if the characters of a string are in lower


case, otherwise False.
isupper() It returns False if characters of a string are in Upper
case, otherwise False.

isspace() It returns True if the characters of a string are


whitespace, otherwise false.

len(string) len() returns the length of a string.

lower() Converts all the characters of a string to Lower case.

upper() Converts all the characters of a string to Upper Case.

startswith(str ,begin=0,end=n) Returns a Boolean value if the string starts with given str
between begin and end.

swapcase() Inverts case of all characters in a string.

lstrip() Remove all leading whitespace of a string. It can also be


used to remove particular character from leading.

rstrip() Remove all trailing whitespace of a string. It can also be


used to remove particular character from trailing.
Examples:

1) capitalize()

1. >>> 'abc'.capitalize()

Output:

'Abc'

2) count(string)

1. msg = "welcome to sssit";


2. substr1 = "o";
3. print [Link](substr1, 4, 16)
4. substr2 = "t";
5. print [Link](substr2)

Output:

>>>
2
2
>>>

3) endswith(string)

1. string1="Welcome to SSSIT";
2. substring1="SSSIT";
3. substring2="to";
4. substring3="of";
5. print [Link](substring1);
6. print [Link](substring2,2,16);
7. print [Link](substring3,2,19);
8. print [Link](substring3);

Output:

>>>
True
False
False
False
>>>

4) find(string)

1. str="Welcome to SSSIT";
2. substr1="come";
3. substr2="to";
4. print [Link](substr1);
5. print [Link](substr2);
6. print [Link](substr1,3,10);
7. print [Link](substr2,19);

Output:

>>>
3
8
3
-1
>>>

5) index(string)
1. str="Welcome to world of SSSIT";
2. substr1="come";
3. substr2="of";
4. print [Link](substr1);
5. print [Link](substr2);
6. print [Link](substr1,3,10);
7. print [Link](substr2,19);

Output:

>>>
3
17
3
Traceback (most recent call last):
File "C:/Python27/[Link]", line 7, in
print [Link](substr2,19);
ValueError: substring not found
>>>

6) isalnum()

1. str="Welcome to sssit";
2. print [Link]();
3. str1="Python47";
4. print [Link]();

Output:

>>>
False
True
>>>
7) isalpha()

1. string1="HelloPython"; # Even space is not allowed


2. print [Link]();
3. string2="This is Python2.7.4"
4. print [Link]();

Output:

>>>
True
False
>>>

8) isdigit()

1. string1="HelloPython";
2. print [Link]();
3. string2="98564738"
4. print [Link]();

Output:

>>>
False
True
>>>

9) islower()

1. string1="Hello Python";
2. print [Link]();
3. string2="welcome to "
4. print [Link]();

Output:

>>>
False
True
>>>

10) isupper()

1. string1="Hello Python";
2. print [Link]();
3. string2="WELCOME TO"
4. print [Link]();

Output:

>>>
False
True
>>>

11) isspace()

1. string1=" ";
2. print [Link]();
3. string2="WELCOME TO WORLD OF PYT"
4. print [Link]();

Output:

>>>
True
False
>>>

12) len(string)

1. string1=" ";
2. print len(string1);
3. string2="WELCOME TO SSSIT"
4. print len(string2);

Output:

>>>
4
16
>>>

13) lower()

1. string1="Hello Python";
2. print [Link]();
3. string2="WELCOME TO SSSIT"
4. print [Link]();

Output:

>>>
hello python
welcome to sssit
>>>

14) upper()

1. string1="Hello Python";
2. print [Link]();
3. string2="welcome to SSSIT"
4. print [Link]();

Output:

>>>
HELLO PYTHON
WELCOME TO SSSIT
>>>

15) startswith(string)

1. string1="Hello Python";
2. print [Link]('Hello');
3. string2="welcome to SSSIT"
4. print [Link]('come',3,7);

Output:

>>>
True
True
>>>

16) swapcase()

1. string1="Hello Python";
2. print [Link]();
3. string2="welcome to SSSIT"
4. print [Link]();

Output:
>>>
hELLO pYTHON
WELCOME TO sssit
>>>

17) lstrip()

1. string1=" Hello Python";


2. print [Link]();
3. string2="@@@@@@@@welcome to SSSIT"
4. print [Link]('@');

Output:

>>>
Hello Python
welcome to world to SSSIT
>>>

18) rstrip()

1. string1=" Hello Python ";


2. print [Link]();
3. string2="@welcome to SSSIT!!!"
4. print [Link]('!');

Output:

>>>
Hello Python
@welcome to SSSIT
>>>

You might also like