Array & String in Python
Array & String in Python
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 :
Once you have imported the ‘array’ module, you can declare an array. Here is
how you do it:
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:
~$ python
So this way we can create a simple python array and print it.
>>> my_array[2]
>>> my_array[0]
>>> 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.
>>> 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.
>>> 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.
>>> 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’.
>>> my_array.remove(13)
>>> my_array
array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
>>> my_array.pop()
12
>>> my_array
array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
>>> my_array.index(5)
5
So we see that the value at index 5 was fetched through this method.
>>> my_array.reverse()
>>> my_array
array('i', [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
>>> my_array.buffer_info()
(33881712, 12)
So we see that buffer start address and number of elements were provided in
output.
>>> my_array.count(11)
1
>>> 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.
>>> my_char_array.fromstring("stuff")
>>> my_char_array
array('c', 'geekstuff')
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.
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.
print(arr[1])
print(arr[2])
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.
print(arr[-2])
50
40
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.
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)
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.
When we print the elements of fruits it shows that Pineapple have replaced Mango at
index 1.
[1, 2, 3, 4, 5, 6]
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].
['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
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.
[1, 2]
[7, 8]
attributes
behavior
Parrot is an object,
The concept of OOP in Python focuses on creating reusable code. This concept is also
known as DRY (Don't Repeat Yourself).
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.
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.
obj = Parrot()
Suppose we have details of parrot. Now, we are going to show how to build the class and
objects of parrot.
# class attribute
species = "bird"
# instance attribute
[Link] = name
[Link] = age
# instantiate the Parrot class
print("Blu is a {}".format(blu.__class__.species))
Run
Powered by DataCamp
Blu is a bird
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.
[Link] = name
[Link] = age
# instance method
def dance(self):
print([Link]("'Happy'"))
print([Link]())
Run
Powered by DataCamp
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).
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):
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.
def __init__(self):
self.__maxprice = 900
def sell(self):
self.__maxprice = price
c = Computer()
[Link]()
c.__maxprice = 1000
[Link]()
[Link](1000)
[Link]()
Run
Powered by DataCamp
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.
def fly(self):
def swim(self):
class Penguin:
def fly(self):
def swim(self):
# common interface
def flying_test(bird):
[Link]()
#instantiate objects
blu = Parrot()
peggy = Penguin()
flying_test(blu)
flying_test(peggy)
Run
Powered by DataCamp
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.
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.
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:
def func(self):
print('Hello')
# Output: 10
print(MyClass.a)
print([Link])
print(MyClass.__doc__)
Run
Powered by DataCamp
10
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.
class MyClass:
a = 10
def func(self):
print('Hello')
# create a new MyClass
ob = MyClass()
print([Link])
print([Link])
# 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).
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:
[Link] = r
[Link] = i
def getData(self):
print("{0}+{1}j".format([Link],[Link]))
c1 = ComplexNumber(2,3)
# Call getData() function
# Output: 2+3j
[Link]()
c2 = ComplexNumber(5)
[Link] = 10
[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'
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
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.
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.
class DerivedClass(BaseClass):
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.
class Polygon:
def __init__(self, no_of_sides):
self.n = no_of_sides
def inputSides(self):
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
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
>>> issubclass(Polygon,Triangle)
False
>>> issubclass(Triangle,Polygon)
True
>>> issubclass(bool,int)
True
Example
class Base1:
pass
class Base2:
pass
In multilevel inheritance, features of the base class and the derived class is inherited into
the new derived class.
class Derived1(Base):
pass
class Derived2(Derived1):
pass
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}
>>> 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
>>> 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
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)]
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
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
>>> 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.
We can add, subtract, multiply, divide, and test equality by using the following relations:
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 __str__(self):
return "%s/%s" % (self.n, self.d)
__repr__ = __str__
>>> 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.
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.
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.
class ParseError(Exception):
pass
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()
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.
>>> 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.
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 integers():
"""Infinite sequence of integers."""
i = 1
while True:
yield i
i = i + 1
def squares():
for i in integers():
yield i * i
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.
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.
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 readfiles(filenames):
for f in filenames:
for line in open(f):
yield line
def printlines(lines):
for line in lines:
print line,
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.
5.4. Itertools
The itertools module in the standard library provides lot of intersting tools to work with
iterators.
>>> 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.
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.
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].
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 "*".
eg:
Output:
'ratanjaiswal'
>>>
Expression Output
'10' + '20' '1020'
NOTE: Both the operands passed for concatenation must be of same type, else it will show an error.
Eg:
'abc' + 3
>>>
output:
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.
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'
String slice can also be used with Concatenation operator to get whole string.
Eg:
1. >>> str="Mahesh"
2. >>> str[:6]+str[6:]
3. 'Mahesh'
find(substring ,beginIndex, It returns the index value of the string where substring is
endIndex) found between begin index and end index.
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.
startswith(str ,begin=0,end=n) Returns a Boolean value if the string starts with given str
between begin and end.
1) capitalize()
1. >>> 'abc'.capitalize()
Output:
'Abc'
2) count(string)
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()
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()
Output:
>>>
Hello Python
welcome to world to SSSIT
>>>
18) rstrip()
Output:
>>>
Hello Python
@welcome to SSSIT
>>>