PROGRAMMING WITH PYTHON
UNIT-II :: ARRAYS,STRINGS,CHARACTERS
Arrays in Python
Arrays
Types of Arrays
Arrays using NumPy
Creating Arrays
Operations on Arrays
Attributes of an Array
reshape(),flatten() methods
Matrices in NumPy
Matrix Addition and Multiplication
PROGRAMMING WITH PYTHON
UNIT-II :: ARRAYS,STRINGS,CHARACTERS
Strings and Characters
Creating Strings
Operations on Strings
Working with Characters
Sorting Strings
Searching Strings
Arrays
An array is defined as a collection of items that are stored
at contiguous memory locations.
It is a container which can hold a fixed number of items,
and these items should be of the same type.
Arrays
Array can be handled in Python by a module named
array
If you create arrays using the array module, all
elements of the array must be of the same type.
TYPES OF ARRAY
Creation of Array
Array in Python can be created by importing
array module.
array(data_type, value_list)
is used to create an array with data type and
value list specified in its arguments.
importing array module and creating array can be done
in following ways
1. import array as arr
array_identifier = arr.array (datatype, value_list)
or
2. from array import *
array_identifier = array (datatype, value_list)
ARRAY METHODS
Python has a set of built-in methods that you can use on
lists/arrays.
append(element)
insert(index , element)
extend(list)
index(element)—first occurence
remove(element)—first occurence
pop()
reverse()
count(element)
Basic Operations
Traverse
Insert
Search
Delete
Update
NUMPY IN PYTHON
NumPy is the fundamental package for scientific
computing in Python.
It is a Python library that provides a multidimensional
array object,various derived objects (such as masked
arrays and matrices), and an assortment of routines for
fast operations on arrays, including mathematical,
logical, shape manipulation, sorting, selecting, I/O,
discrete Fourier transforms, basic linear algebra, basic
statistical operations, random simulation and much more.
NUMPY IN PYTHON
At the core of the NumPy package, is the ndarray object.
This encapsulates n-dimensional arrays of homogeneous
data types.
There are several important differences between NumPy
arrays and the standard Python sequences:
NUMPY IN PYTHON
NumPy arrays have a fixed size at creation, unlike
Python lists (which can grow dynamically). Changing
the size of an ndarray will create a new array and delete
the original.
The elements in a NumPy array are all required to be of
the same data type, and thus will be the same size in
memory.
NumPy arrays facilitate advanced mathematical and
other types of operations on large numbers of data.
NUMPY IN PYTHON
The array object in NumPy is called ndarray.
We can create a NumPy ndarray object by using the array()
function.
NUMPY IN PYTHON
There are 6 general mechanisms for creating arrays:
Conversion from other Python structures (i.e. lists and tuples)
Intrinsic NumPy array creation functions (e.g. arange, ones, zeros,
etc.)
Replicating, joining, or mutating existing arrays
Reading arrays from disk, either from standard or custom formats
Creating arrays from raw bytes through the use of strings or
buffers
Use of special library functions (e.g., random)
CREATING NUMPY ARRAYS
Converting from other Python structures-Lists &
Tuples
NumPy arrays can be defined using Python sequences such as
lists and tuples.
Lists and tuples can define ndarray creation:
Example : a=np.array([(1,2,3),(4,5,6)])
a1D = np.array([1, 2, 3, 4])
a2D = np.array([[1, 2], [3, 4]])
a3D = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
CREATING NUMPY ARRAYS
Using Numpy functions
Creating a One-dimensional Array
arange-function
numpy.arange creates arrays with regularly
incrementing values.
Syntax:
arange([start,] stop[, step,][, dtype])
start : [optional] start of interval range. By default start
=0
stop : end of interval range
step : [optional] step size of interval. By default step
size = 1,
dtype : type of output array
Example :
np.arange(10)
output: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
np.arange(2, 10, dtype=float)
output: array([ 2., 3., 4., 5., 6., 7., 8., 9.])
np.arange(2, 3, 0.1)
output:
array([ 2. , 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9])
Ar=np.arange(20)
Ar.shape
Ar1=np.arange(20).reshape(4,5)
Ar1.shape
Ar2=np.arange(27).reshape(3,3,3)
Ar2.shape
Shape--The shape of an array can be defined as the number
of elements in each dimension..
Dimension is the number of indices or subscripts, that we require
in order to specify an individual element of an array
zeros-Return a new array of given shape and type, filled with
zeros
numpy.zeros(shape, dtype=float, order='C', *, like=None)
Ex: np.zeros(5)
np.zeros((5,), dtype=int)
np.zeros((2,1))
PARAMETERS OF ZEROS FUNCTION
shape int or tuple of ints --Shape of the new array, e.g., (2,
3) or 2.
dtype--data-type, optional The desired data-type for the
array, e.g., numpy.int8. Default is numpy.float64.
order{‘C’, ‘F’}, optional, default: ‘C’Whether to store
multi-dimensional data in row-major (C-style) or
column-major (Fortran-style) order in memory.
like array_likeReference object to allow the creation of
arrays which are not NumPy arrays.
ones---Return a new array of given shape and type, filled with
ones.
numpy.ones(shape, dtype=None, order='C', *, like=None)
np.ones(5)
np.ones((5,), dtype=int)
np.ones((2,1))
full---Return a new array of given shape and type, filled with
fill_value
numpy.full (shape, fillvalue, dtype=None, order='C', *, like=None)
shape-int or sequence of ints Shape of the new array, e.g., (2, 3) or 2.
fill_value scalar or array_like Fill value.
dtype data-type, optional The desired data-type for the array
order{‘C’, ‘F’}, optional Whether to store multidimensional data in C- or
Fortran-contiguous (row- or column-wise) order in memory.
like array_likeReference object to allow the creation of arrays which are not
NumPy arrays.
full—
Examples:
np.full((2,2),10)
np.full((2,2),[1,2])
eye—The eye() function is used to create a 2-D array with ones
on the diagonal and zeros elsewhere
numpy.eye(N, M=None, k=0, dtype=<class 'float'>, order='C‘, like=None)
N Number of rows in the output. Required
M Number of columns in the output. If None, defaults to N. optional
k Index of the diagonal: 0 (the default) refers to the main diagonal, a
positive value refers to an upper diagonal, and a negative value to a
lower diagonal. optional
dtype Data-type of the returned array. optional
order Whether the output should be stored in row-major (C-style) or
column-major (Fortran-style) order in memory optional
np.eye(2)
np.eye(2,2)
np.eye(2,3)
np.eye(3,3)
identity--Return the identity array.The identity array is a
square array with ones on the main diagonal.
numpy.identity( n , dtype = none , like=none)
np.identity(3)
OPERATIONS ON NUMPY ARRAYS
numpy.add(arr1,arr2)
numpy.subtract(arr1,arr2)
numpy.multiply(arr1,arr2)
numpy.divide(arr1,arr2)
numpy.mod(arr1,arr2)-This function returns the remainder of
division of the corresponding elements in the input array.
numpy.power(arr1,arr2)
This function treats elements in the first input array as the base and returns
it raised to the power of the corresponding element in the second input
array.
OPERATIONS ON NUMPY ARRAYS
numpy.reciprocal()—
This function returns the reciprocal of argument, element-wise. For
elements with absolute values larger than 1, the result is always 0
and for integer 0, overflow warning is issued.
ATTRIBUTES OF AN ARRAY
ndmin
size
shape
dtype
itemsize
nbytes
T
ATTRIBUTES OF AN ARRAY
1. ndim- This attribute tells the number of array dimensions
Ex:
import numpy as np
x = np.array([1, 2, 3, 4, 5])
print('Number of dimensions in x:', x.ndim)
y = np.array([[11, 12, 13, 14], [32, 33, 34, 35]])
print('Number of dimensions in y:', y.ndim)
z = np.array([[[11, 12, 13, 14], [32, 33, 34, 35]],
[[55, 56, 57, 58], [59, 60, 61, 62]]])
print('Number of dimensions in z:', z.ndim)
ATTRIBUTES OF AN ARRAY
2 size:- This attribute shows the number of elements
present in the array.
3. shape- This array attribute returns a tuple consisting of
array dimensions. It can also be used to resize the
array.
Ex: import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print a.shape /// output (2,3)
a.shape=(3,2)
ATTRIBUTES OF AN ARRAY
4. dtype- dtype tells the data type of the elements of a
NumPy array. In NumPy array, all the elements
have the same data type.
import numpy as np
x = np.array([1, 2, 3, 4, 5])
print('The data type of array x is', x.dtype)
y = np.array([[1 + 2j, 14.478], [5 + 11j, 34]])
print('The data type of array y is', y.dtype)
ATTRIBUTES OF AN ARRAY
5. itemsize- itemsize returns the size (in bytes) of each
element of a NumPy array.
import numpy as np
x = np.array([1,2,3,4,5], dtype = np.int8)
print x.itemsize
6. nbytes-total no of bytes occupied by an array
nbytes= itemsize * size
Print x.nbytes
ATTRIBUTES OF AN ARRAY
T-This attribute returns the transpose of a
matrix
x.T
RESHAPE METHOD
numpy.reshape() :
Gives a new shape to an array without changing its data.
Syn : numpy.reshape(a, newshape, order='C')
a---array to be reshaped
newshape--- int or tuple of ints
FLATTEN METHOD
ndarray.flatten(order='C')
Return a copy of the array collapsed into one dimension.
order—C,F,A,K
‘C’ means to flatten in row-major (C-style) order.
‘F’ means to flatten in column-major (Fortran- style) order.
‘A’ means to flatten in column-major order if a is Fortran contiguous in
memory, row-major order otherwise.
‘K’ means to flatten a in the order the elements occur in memory.
a = np.array([[1,2], [3,4]])
a.flatten()
array([1, 2, 3, 4])
a.flatten('F')
array([1, 3, 2, 4])
MATRICES IN NUMPY
class numpy.matrix(data, dtype=None)
data : data needs to be array-like or string
dtype : Data type of returned array.
This class returns a matrix from a string of data or array-like
object.
>>> a = np.matrix('1 2; 3 4')
>>> a
matrix([[1, 2],
[3, 4]])
MATRICES IN NUMPY
Example:
>>>np.matrix([[1, 2], [3, 4]])
matrix([[1, 2],
[3, 4]])
MATRIX OPERATIONS
import numpy as np
x = np.matrix([[1, 2], [4, 5]])
y = np.matrix([[7, 8], [9, 10]])
Addition
np.add(x,y)
Subtraction
np.subtract(x,y)
Multiply
np.multiply(x,y)
np.dot(x,y)
STRINGS IN PYTHON
A String is a sequence of characters. It is a derived data type.
Strings are immutable.
Python strings can be created with single quotes, double quotes, or
triple quotes.
When we use triple quotes, strings can span several lines without
using the escape character.
Creating strings is as simple as assigning a value to a variable.
For example −
var1 = 'Hello World!'
var2 = "Python Programming"
STRINGS IN PYTHON
Multiline Strings
We can assign a multiline string to a variable by using three
quotes:
Ex: a=‘ ‘ ‘one can assign a multiline
string to a variable by using
three quotes ’ ’ ’
STRINGS IN PYTHON
Python does not have a character data type, a single character
is simply a string with a length of 1.
Square brackets can be used to access elements of the string.
Example :
a = "Hello, World!"
print(a[1]) /// prints character-’e’ of index:1
Looping through String
Since strings are arrays, we can loop through the characters in a
string, with a for loop.
Ex: for x in "banana":
print(x) // prints each character
STRINGS IN PYTHON
String Length
To get the length of a string, use the len() function.
Ex: a = "Hello, World!"
print(len(a)) // outputs- 13
Check String
To check if a certain phrase or character is present in a string,
we can use the keyword in.
Ex: txt = "The best things in life are free!"
print("free" in txt) //returns true
STRINGS IN PYTHON
Check if NOT
To check if a certain phrase or character is NOT present in a
string, we can use the keyword not in.
Ex: txt = "The best things in life are free!"
print("expensive" not in txt)
STRINGS IN PYTHON
String Special Operators
Assume string variable a ='Hello' , b = 'Python', then
STRINGS IN PYTHON
Slicing Strings
We can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a
colon, to return a part of the string.
Ex: b = "Hello, World!"
print(b[2:5])
Get the characters from position 2 to position 5 (not included)
STRINGS IN PYTHON
Slice from the Start
Get the characters from the start to position 5 (not
included):
Ex: b = "Hello, World!"
print(b[:5])
Slice To the End
By leaving out the end index, the range will go to the
end:
Ex: b = "Hello, World!"
print(b[2:])
STRINGS IN PYTHON
Negative Indexing
Use negative indexes to start the slice from the end of
the string:
Example
Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):
Ex: b = "Hello, World!"
print(b[-5:-2])
output : orl
STRINGS IN PYTHON
Modify Strings
The upper() method returns the string in upper case
a = "Hello, World!"
print(a.upper())
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
Remove Whitespace
Whitespace is the space before and/or after the actual text
STRINGS IN PYTHON
The strip() method removes any whitespace from the beginning
or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
Replace String
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
STRINGS IN PYTHON
Split String
The split() method returns a list where the text between the
specified separator becomes the list items.
Ex:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
String Concatenation
To concatenate, or combine, two strings you can use the +
operator.
STRINGS IN PYTHON
Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c=a+b
print(c)
To add a space between them, add a " ":
a = "Hello"
b = "World"
c=a+""+b
print(c)
STRINGS IN PYTHON
String Format
The format() method takes the passed arguments, formats
them, and places them in the string where the placeholders {}
are:
Use the format() method to insert numbers into strings:
Ex : age = 36
txt = "My name is vijay, and I am {}"
print(txt.format(age))
o/p: My name is vijay, and I am 36
STRINGS IN PYTHON
The format() method takes unlimited number of arguments,
and are placed into the respective placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
o/p: I want 3 pieces of item 567 for 49.95 dollars
STRINGS IN PYTHON
Use index numbers {0} to be sure the arguments are placed in
the correct placeholders
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item
{1}."
print(myorder.format(quantity, itemno, price))
o/p: I want to pay 49.95 dollars for 3 pieces of item 567
STRINGS IN PYTHON
Other String Methods
capitalize()-- Converts the first character to upper case
count() ---Returns the number of times a specified value occurs in a
string
endswith()----Returns true if the string ends with the specified value
find() -----Searches the string for a specified value and returns the
position of where it was found.
index()----Searches the string for a specified value and returns the
position of where it was found
isalnum()Returns True if all characters in the string are
alphanumeric
isalpha()Returns True if all characters in the string are in
the alphabet
isdecimal()Returns True if all characters in the string are
decimals
isdigit()Returns True if all characters in the string are
digits
isidentifier()Returns True if the string is an identifier
OTHER STRING METHODS
islower()Returns True if all characters in the string are
lower case
isnumeric()Returns True if all characters in the string
are numeric
swapcase()Swaps cases, lower case becomes upper case
and vice versa
SORTING STRING
The sorted() function returns a sorted list of the specified
iterable object.
We can specify ascending or descending order. Strings are
sorted alphabetically, and numbers are sorted numerically.
Syntax:
sorted(iterable, key=key, reverse=reverse)
iterable Required. The sequence to sort, list, dictionary, tuple etc.
key Optional. A Function to execute to decide the order. Default is
None
reverse Optional. A Boolean. False will sort ascending, True will sort
descending. Default is False
SORTING STRING
Sort Ascending
a = ("h", "b", "a", "c", "f", "d", "e", "g")
x = sorted(a)
print(x)
Sort Descending
a = ("h", "b", "a", "c", "f", "d", "e", "g")
x = sorted(a, reverse=True)
print(x)
SEARCHING STRING
The find() method finds the first occurrence of the
specified value.
The find() method returns -1 if the value is not found.
Syntax:
string.find(value, start, end)
value Required. The value to search for
start Optional. Where to start the search. Default is 0
end Optional. Where to end the search. Default is to the
end of the string
SEARCHING STRING
Ex :
txt = "Hello, welcome to my world."
x = txt.find("e")
x = txt.find("e", 5, 10)
print(txt.find("q"))
print(txt.index("q"))