0% found this document useful (0 votes)
4 views

Module and Strings

The document provides an overview of Python modules, explaining their purpose, how to import them, and the structure of namespaces and scoping. It also covers string data types, operations, and built-in functions related to strings, including concatenation, indexing, and slicing. Additionally, it discusses the use of the 'in' operator for string comparison and the availability of string functions in Python's string library.

Uploaded by

Quadri Alayo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Module and Strings

The document provides an overview of Python modules, explaining their purpose, how to import them, and the structure of namespaces and scoping. It also covers string data types, operations, and built-in functions related to strings, including concatenation, indexing, and slicing. Additionally, it discusses the use of the 'in' operator for string comparison and the availability of string functions in Python's string library.

Uploaded by

Quadri Alayo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Python - Modules

CSC 301
What are Modules?

• Modules are files containing Python definitions and statements


(ex. name.py)
• A module’s definitions can be imported into other modules by
using “import name”
• The module’s name is available as a global variable value
• To access a module’s functions, type “name.function()”
Python - Modules
• A module allows you to logically organize your Python code. Grouping related
code into a module makes the code easier to understand and use.
• A module is a Python object with arbitrarily named attributes that you can bind and
reference.
• Simply, a module is a file consisting of Python code. A module can define
functions, classes, and variables. A module can also include runnable code.
• Example:
• The Python code for a module named aname normally resides in a file named
aname.py. Here's an example of a simple module, hello.py
def print_func( par ):
print "Hello : ", par
return
The import Statement:
• You can use any Python source file as a module by executing an import statement
in some other Python source file. import has the following syntax:
import module1[, module2[,... moduleN]
• When the interpreter encounters an import statement, it imports the module if the
module is present in the search path. A search path is a list of directories that the
interpreter searches before importing a module.
• Example:
import hello
hello.print_func("Zara")
This would produce following result:
Hello : Zara
• A module is loaded only once, regardless of the number of times it is imported.
This prevents the module execution from happening over and over again if
multiple imports occur.
The from...import * Statement:
It is also possible to import all names from a module into the current namespace by
using the following import statement:
from modname import *
• This provides an easy way to import all the items from a module into the current
namespace; however, this statement should be used sparingly.
Locating Modules:
When you import a module, the Python interpreter searches for the module in the
following sequences:
• The current directory.
• If the module isn't found, Python then searches each directory in the shell variable
PYTHONPATH.
• If all else fails, Python checks the default path. On UNIX, this default path is
normally /usr/local/lib/python/.
The module search path is stored in the system module sys as the sys.path variable.
The sys.path variable contains the current directory, PYTHONPATH, and the
installation-dependent default.
The PYTHONPATH Variable:
• The PYTHONPATH is an environment variable, consisting of
a list of directories. The syntax of PYTHONPATH is the same
as that of the shell variable PATH.
• Here is a typical PYTHONPATH from a Windows system:
set PYTHONPATH=c:\python20\lib;
• And here is a typical PYTHONPATH from a UNIX system:
set PYTHONPATH=/usr/local/lib/python
Namespaces and Scoping:
• Variables are names (identifiers) that map to objects. A
namespace is a dictionary of variable names (keys) and their
corresponding objects (values).
• A Python statement can access variables in a local namespace
and in the global namespace. If a local and a global variable
have the same name, the local variable shadows the global
variable.
• Each function has its own local namespace. Class methods
follow the same scoping rule as ordinary functions.
• Python makes educated guesses on whether variables are local
or global. It assumes that any variable assigned a value in a
function is local.
Namespaces and Scoping:
• Therefore, in order to assign a value to a global variable
within a function, you must first use the global statement.
• The statement global VarName tells Python that VarName is a
global variable. Python stops searching the local namespace
for the variable.
• For example, we define a variable Money in the global
namespace. Within the function Money, we assign Money a
value . therefor Python assumes Money is a local variable.
However, we access the value of the local variable Money
before setting it, so an UnboundLocalError is the result.
Uncommenting the global statement fixes the problem.
Example:

Money = 2000
def AddMoney():
Money = Money + 1

print Money
AddMoney()
print Money
The dir( ) Function:
• The dir() built-in function returns a sorted list of strings containing the names
defined by a module.
• The list contains the names of all the modules, variables, and functions that are
defined in a module.
• Example:
import math
content = dir(math)
print (content);
• This would produce following result:
['__doc__', '__name__', '__package__', 'acos',
'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh',
'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e',
'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial',
'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot',
'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10',
'log1p', 'modf', 'pi', 'pow', 'radians', 'sin',
'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
The globals() and locals() Functions:
• The globals() and locals() functions can be used to return the names in the global
and local namespaces depending on the location from where they are called.
• If locals() is called from within a function, it will return all the names that can be
accessed locally from that function.
• If globals() is called from within a function, it will return all the names that can
be accessed globally from that function.
• The return type of both these functions is dictionary. Therefore, names can be
extracted using the keys() function.
The reload() Function:
• When the module is imported into a script, the code in the top-level portion of a module is executed only
once.
• Therefore, if you want to reexecute the top-level code in a module, you can use the reload() function.
The reload() function imports a previously imported module again.
• Syntax:
The syntax of the reload() function is this:
reload(module_name)
Here module_name is the name of the module you want to reload and not the string containing the
module name. For example to re-load hello module, do the following:
reload(hello)
Packages in Python:
Example:
Consider a file Pots.py available in Phone directory. This file has following
line of source code:
def Pots():
print "I'm Pots Phone"
Similar way we have another two files having different functions with the
same name as above:
Phone/Isdn.py file having function Isdn()
Phone/G3.py file having function G3()
Now create one more file __init__.py in Phone directory :
Phone/__init__.py
To make all of your functions available when you've imported Phone, you
need to put explicit import statements in __init__.py as follows:
from Pots import Pots
from Isdn import Isdn
from G3 import G3

Note: Application file (e.g. package.py) should be saved in the parent


directory of Phone sub-directory.
Sources

• http://docs.python.org/tutorial/modules.html
Strings

CSC 301
String Data Type >>> str1 = "Hello”
• A string is a sequence of >>> str2 = 'there'
>>> bob = str1 + str2
characters >>> print bob
• A string literal uses quotes Hellothere
'Hello' or “Hello” >>> str3 = '123'
>>> str3 = str3 + 1
• For strings, + means Traceback (most recent call last):
“concatenate” File "<stdin>", line 1, in
• When a string contains <module>TypeError: cannot
numbers, it is still a string concatenate 'str' and 'int' objects
>>> x = int(str3) + 1
• We can convert numbers in a >>> print x
string into a number using 124
int() >>>
Reading and Converting
>>> name = input('Enter:')
• We prefer to read data Enter:Chuck
in using strings and then >>> print name
parse and convert the Chuck
data as we need >>> apple = input('Enter:')
Enter:100
• This gives us more
>>> x = apple – 10
control over error Traceback (most recent call last):
situations and/or bad File "<stdin>", line 1, in
user input <module>TypeError: unsupported
operand type(s) for -: 'str' and 'int'
• Raw input numbers
>>> x = int(apple) – 10
must be converted from >>> print x
strings 90
Looking Inside Strings

• We can get at any single


b a n a n a
character in a string using an
0 1 2 3 4 5
index specified in square
brackets >>> fruit = 'banana'
>>> letter = fruit[1]
• The index value must be an >>> print letter
integer and starts at zero a
• The index value can be an >>> n = 3
>>> w = fruit[n - 1]
expression that is computed >>> print w
n
A Character Too Far

• You will get a python error


if you attempt to index >>> zot = 'abc'
beyond the end of a string. >>> print (zot[5])
Traceback (most recent call last):
• So be careful when File "<stdin>", line 1, in
constructing index values <module>IndexError: string index
and slices out of range
>>>
Strings Have Length

• There is a built-in function len


that gives us the length of a b a n a n a
string
0 1 2 3 4 5

>>> fruit = 'banana'


>>> print( len(fruit))
6
Len Function

A function is some
>>> fruit = 'banana'
stored code that we
>>> x = len(fruit)
use. A function takes
>>> print (x)
some input and
6
produces an output.

'banana' len() 6
(a string) function (a number)
Len Function

A function is some
>>> fruit = 'banana'
stored code that we
>>> x = len(fruit)
use. A function takes
>>> print (x)
some input and
6
produces an output.

def len(inp):
blah
'banana' blah 6
for x in y: (a number)
(a string) blah
blah
Looping Through Strings

• Using a while statement


and an iteration variable,
fruit = 'banana' 0b
and the len function, we index = 0 1a
can construct a loop to while index < len(fruit) : 2n
look at each of the letters letter = fruit[index] 3a
in a string individually print (index, letter) 4n
index = index + 1 5a
Looping Through Strings

• A definite loop using a


for statement is much
b
more elegant a
• The iteration variable is fruit = 'banana' n
for letter in fruit : a
completely taken care of print (letter)
by the for loop n
a
Looping Through Strings

• A definite loop using a


fruit = 'banana'
for statement is much
for letter in fruit : b
more elegant print letter a
• The iteration variable is n
completely taken care of index = 0
a
by the for loop while index < len(fruit) : n
a
letter = fruit[index]
print (letter)
index = index + 1
Looping and Counting

• This is a simple loop that


loops through each letter
in a string and counts the word = 'banana'
number of times the loop count = 0
for letter in word :
encounters the 'a' if letter == 'a' :
character. count = count + 1
print (count)
Looking deeper into in
• The iteration variable
“iterates” though the
sequence (ordered set)
• The block (body) of code Six-character string
Iteration variable
is executed once for each
value in the sequence
for letter in 'banana' :
• The iteration variable
print letter
moves through all of the
values in the sequence
Yes b a n a n a
Done? Advance letter

print letter

for letter in 'banana' :


print (letter)

The iteration variable “iterates” though the string and the


block (body) of code is executed once for each value in the
sequence
• We can also look at any M o n t y P y t h o n
continuous section of a 0 1 2 3 4 5 6 7 8 9 10 11
string using a colon
operator >>> s = 'Monty Python'
• The second number is >>> print s[0:4]
Mont
one beyond the end of the >>> print s[6:7]
slice - “up to but not P
including” >>> print s[6:20]
• If the second number is Python
beyond the end of the
string, it stops at the end Slicing Strings
M o n t y P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11

• If we leave off the first >>> s = 'Monty Python'


number or the last >>> print s[:2]
number of the slice, it is Mo
>>> print s[8:]
assumed to be the
Thon
beginning or end of the >>> print s[:]
string respectively Monty Python

Slicing Strings
String Concatenation

• When the + operator >>> a = 'Hello'


is applied to strings, >>> b = a + 'There'
it means >>> print b
"concatenation" HelloThere
>>> c = a + ' ' + 'There'
>>> print( c)
Hello There
>>>
Using in as an Operator

• The in keyword can >>> fruit = 'banana’


>>> 'n' in fruit
also be used to check True
to see if one string is >>> 'm' in fruit
False
"in" another string >>> 'nan' in fruit
• The in expression is a True
>>> if 'a' in fruit :
logical expression and ... print 'Found it!’
returns True or False ...
Found it!
and can be used in an if >>>
statement
String Comparison

if word == 'banana':
print 'All right, bananas.'

if word < 'banana':


print 'Your word,' + word + ', comes before banana.’
elif word > 'banana':
print 'Your word,' + word + ', comes after banana.’
else:
print 'All right, bananas.'
String Library
• Python has a number of string
functions which are in the string
library
• These functions are already >>> greet = 'Hello Bob'>>> zap
built into every string - we = greet.lower()>>> print
zaphello bob
invoke them by appending the >>> print greet
function to the string variable Hello Bob>>> print 'Hi
• These functions do not modify There'.lower()
the original string, instead they hi there
>>>
return a new string that has been
altered
>>> stuff = 'Hello world’
>>> type(stuff)<type 'str'>
>>> dir(stuff)
['capitalize', 'center', 'count', 'decode', 'encode', 'endswith',
'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit',
'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']

http://docs.python.org/lib/string-methods.html
http://docs.python.org/lib/string-methods.html
String Library

str.capitalize() str.replace(old, new[, count])


str.center(width[, fillchar]) str.lower()
str.endswith(suffix[, start[, end]]) str.rstrip([chars])
str.find(sub[, start[, end]]) str.strip([chars])
str.lstrip([chars]) str.upper()

http://docs.python.org/lib/string-methods.html
Searching a String
• We use the find()
function to search for a b a n a n a
substring within another
0 1 2 3 4 5
string
• find() finds the first >>> fruit = 'banana'
occurance of the >>> pos = fruit.find('na')
>>> print (pos)
substring 2
• If the substring is not >>> aa = fruit.find('z')
found, find() returns -1 >>> print (aa)
-1
• Remember that string
position starts at zero
Making everything UPPER CASE

• You can make a copy of a string


in lower case or upper case >>> greet = 'Hello Bob'
>>> nnn = greet.upper()
• Often when we are searching >>> print nnn
for a string using find() - we HELLO BOB
first convert the string to lower >>> www = greet.lower()
case so we can search a string >>> print www
hello bob
regardless of case
>>>
Search and Replace
• The replace()
function is like a
“search and
replace” operation >>> greet = 'Hello Bob'
in a word processor >>> nstr = greet.replace('Bob','Jane')
>>> print nstr
• It replaces all
Hello Jane
occurrences of the >>> nstr = greet.replace('o','X')
search string with >>> print nstrHellX BXb
the replacement >>>
string
Stripping Whitespace
• Sometimes we want to
take a string and remove
whitespace at the >>> greet = ' Hello Bob '
beginning and/or end >>> greet.lstrip()
• lstrip() and rstrip() to the 'Hello Bob '
>>> greet.rstrip()
left and right only
' Hello Bob'
• strip() Removes both >>> greet.strip()
begin and ending 'Hello Bob'
whitespace >>>
Prefixes

>>> line = 'Please have a nice day’


>>> line.startswith('Please')
True
>>> line.startswith('p')
False
Summary

• String type
• Read/Convert
• Indexing strings []
• Slicing strings [2:4]
• Looping through strings with for and while
• Concatenating strings with +
• String operations

You might also like