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

PPS Unit 3 PPT

Unit 3 covers functions and strings in Python, emphasizing the need for functions to enhance code reusability and modularity. It discusses defining functions, variable scope, lifetime, and the use of built-in and user-defined functions, along with string operations and formatting. Additionally, it introduces modules and packages, highlighting their importance in organizing and reusing code.

Uploaded by

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

PPS Unit 3 PPT

Unit 3 covers functions and strings in Python, emphasizing the need for functions to enhance code reusability and modularity. It discusses defining functions, variable scope, lifetime, and the use of built-in and user-defined functions, along with string operations and formatting. Additionally, it introduces modules and packages, highlighting their importance in organizing and reusing code.

Uploaded by

shivamshirke07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Unit 3

Functions and Strings


Syllabus :
• Need for functions, Function: definition, call, variable scope and
lifetime, the return statement. Defining functions, Lambda or
anonymous function, documentation string, good programming
practices. Introduction to modules, Introduction to packages in
Python, Introduction to standard library modules.
• Strings and Operations- concatenation, appending, multiplication
and slicing. Strings are immutable, strings formatting operator, built
in string methods and functions. Slice operation, ord() and chr()
functions, in and not in operators, comparing strings, Iterating
strings, the string module.
Need for Functions:
• Code reusability.
• Dividing the program into separate well-defined function Simplify the process of program
development.
• Easy to understand, code, test
• Memory space is limited.
• They help program to be modular. Means they help in writing small parts of a program which are
meaningful.These small parts (modules) can be used again and again at different places in a
program.
• Large program should follow DRY( Don’t Repeat Yourself) principle, bad programming is
WET(Write Everything Twice) or (We Enjoy Typing) principle.
Python has two types of functions.
1. Built in function. Ex- max(), min(),print()
2. User Defined Function-
Ex- def f1():
print("welcome to function f1")
f1()
Definition of functions :
• A function is a block of organized and reusable program code that perform single, specific and
well-defined task.
• A function f that uses another function g, is known as the calling function and g is known as the
called function.
• Note :Function name cannot contain spaces or special characters except underscore (–). Does not
start with numbers.
The definition of a function includes:
The def keyword (which stands for define).
The function name.
Parameters in parentheses (inputs to the function).
A colon :
The indented block of code that runs when the function is called.
Syntax :
def function_name(parameters):
……
…….
return value
Definition of functions :

• Example- Write a program to add • Output


two numbers using a function
Add= 300
def add(a,b):
c=a+b
return c
res=add(100,200)
print("Add=",res)
Call to a function :
• A function can be called from any place in python script.
• Place or line of call of function should be after place or line of
declaration of function.
• Example:
Function Definition: add(a, b) is created to take two numbers and return their sum.
Function Call: add(100, 200) is invoked with 100 and 200 as arguments.
Computation: Inside the function, c = 100 + 200 evaluates to 300.
Return Value: The function returns 300, which is stored in res.
Printing the Output: print("Add=", res) outputs Add= 300 to the console.
Call to a function :
Example on Function call:
• Example1- Function calling single time • Example2- Function calling Multiple
def f1(): time.
print("I am in f1 function") def f1():
f1() # Function calling print("I am in f1 function")
------------------------------------ f1() # Function calling
Output f1()# Function calling
I am in f1 function f1()# Function calling
--------------------------------------
Output
I am in f1 function
I am in f1 function
I am in f1 function
Example on Function call:
• Example 3- Function calling Output
another function. I am in f2 function
def f1(): I am in f1 function
print("I am in f1 function")
def f2():
print("I am in f2 function")
f1()
f2()
Variable Scope and Lifetime :
• Scope of variable- part of program in which a variable is accessible is called a scope.
• Lifetime of a variable- Duration for which the variable exists is called its lifetime.
• In functions, there are two kinds of variables, local and global.
Local Variables / Objects :
• The variable which are declare inside a function are called local variable.
• From outside of function we cannot access. Local variable is available to function
in which we are declare it.
• Variables or objects which are used only within given function are local variables or
local objects.
• Local objects include parameters and any variable / object which is created in a
given function.
Variable Scope and Lifetime
• Example on Local Variable • Output
def f1(): a value in f1: 10
a=10 # local variable NameError: name 'a' is
print("a value in f1:",a) not defined
def f2():
print("a value in f2:",a)#can not access
f1()
f2()
Variable Scope and Lifetime
• Global variables / objects :
• Objects which can be accessed throughout the script/program are global variables or objects.
• Global variables or objects are created in python script outside any function.
• Global objects are available after “global” keyword defined in the script.
• Example on global variable
a=20 # global variable
def f1():
print("a value in f1 function",a)
f1()
print("a value outside function",a)
----------------------------------------------------
Output
a value in f1 function 20
a value outside function 20
Variable Scope and Lifetime
Example 2- Global variable and local • Output
variable. global variable num1 10
num1=10 # global variable
in function- local variable num2= 20
print("global variable num1", num1) in function local variable num3= 30
def func(num2): num1 again 10
print("in function- local variable num2=",
num2)
num3=30 # local variable
print("in function local variable num3=",
num3)
func(20)
print("num1 again", num1)
# print("num3 outside function =",num3) Error-
global keyword
• If local variable and global variable has same name then the function by default refers to the local
variable and ignores the global variable.
• If we want to access global variable inside a function we can access it by using global variable.
Ex-
a=10
def f1():
global a
a=20
print("a is",a)
def f2():
print("a is",a)
f1()
f2()
print("a is",a)
Return Statement :
• It is statement to return from a function to its previous function who
called this function.
• After return control goes out of the current function.
• All local variables which were allocated memory in current function
will be destroyed.
• Return statement is optional in python.
• Any function can return multiple arguments.
Return Statement :
Example
• return #This returns none value
• return None #This returns none value
• return a, b #This returns two values
• return a #This returns single value
These all are valid examples of a return statement.
• Example 1
def f1():
print("Hello")
return
print(f1())
---------------------------------------------
Output
Hello
None
Return Statement:
Example 2: Example 3:
def add(a,b): def calculation(a,b):
add=a+b
c=a+b
sub=a-b
return c mul=a*b
z=add(10,20) div=a/b
print("Add=",z) return add, sub, mul, div
-------------------------------------- z=calculation(10,2)
print(z)
Output
-------------------------------------------
Add= 30
Output
(12, 8, 20, 5.0)
Defining Functions
➢ def → Keyword to define a function.
➢ function_name → The name of the function (should be descriptive).
➢parameters → Inputs (optional).
➢return → Sends back a value (optional).
Syntax :
def function_name(parameters):
……
…….
return value
Defining Functions
Example- Output
def swap(a,b): Enter a value100
temp=a Enter b value200
a=b After swap a= 200
b=temp After swap b= 100
print("After swap a=",a)
print("After swap b=",b)
a=int(input("Enter a value"))
b=int(input("Enter b value"))
swap(a,b)
Arguments/ parameter to a Function :
• A function may accept arguments or it may not accept any
arguments or parameters.
• Arguments or Parameters to a function are treated as local
variable for that function.
• While defining the function, number of parameters has to be
specified as sequence of variables.
There are different types of arguments :
• Required arguments
• Keyword Arguments
• Default Arguments
• Variable-length arguments
Required arguments
Required arguments
• The argument is passed to a function in correct positional order.
• These arguments are passed to function based on their position.
• Any normal arguments are positional arguments
• Number of argument in the function call should exactly match with the number of
arguments specified in the function definition.
Ex 1-
def display(s):
print(s)
display("Hello")
-----------------------------------
Hello
Example of Required Arguments
Example of Required Arguments :
def display(name, age):
print("name:",name)
print("age:", age)
display("ABC","20")
-----------------------------------------------
Output
name: ABC
age: 20
Keyword Arguments
Keyword Arguments
• These are another special category of arguments supported in python.
• Here arguments are passed in format “key=value” or name value
• Order is not important.
• number of argument is required.
Ex-
def display(name, age):
print("name:",name)
print("age:", age)
display(age=10,name="ABC")
--------------------------------------
name: ABC
age: 10
Default Arguments
Default Arguments
• One of the argument to a function may have its default value.
• For example laptop has default built-in speakers. So if no speaker is
connected it will play default speaker.
• Similarly in function argument, a default value can be assigned to an
argument.
• Now if value for this argument is not passed by the user then
function will consider that arguments default value.
• Calling functions with very large number of arguments can be made
easy by default values
Example of Default Arguments :
Example of Default Arguments :
def display(name, age,college=SKNCOE):
print("name:",name)
print("age:", age)
print("College=",college)
display(age=10,name="ABC")
---------------------------------------------------------------------------
name: ABC
age: 10
College= SKNCOE
Variable length arguments
Variable length arguments
• Variable length argument is an argument that can accept any number
of values.
• Variable length arguments written with * symbol.
• It store all values in tuple.
Syntax
def function_name([arg1, arg2,….] * var_args_tuple):
function statement
return expression
Variable length arguments
Example- 1
def display(year, *subjects):
print("Year=",year)
print("Subjects=", subjects)
display("FE","PPS","M1","Eng. Chemistry","Eng, Physics")
--------------------------------------------------
o/p
Year= FE
Subjects= ('PPS', 'M1', 'Eng. Chemistry', 'Eng, Physics')
Variable length arguments
Ex2- Ex- 3
def ABC(*num): def ABC(*num):
print(num) print(num[0])
ABC(4,5,6) print(num[1])
---------------------- print(num[2])
(4, 5, 6) ABC(4,5,6)
-------------------------------------
4
5
6
Lambda / Anonymous Functions :
• Lambda function not declare using def keyword, It is created by using lambda
keyword.
• Lambda function are throw away function, i.e. they are just needed where
they have been created and can be used anywhere a function is required.
• Lambda function have no name.
• We use lambda functions when we require a nameless function for a short
period of time.
• lambda function can take any number of arguments.
• Functions containing only single operation can be converted into an
anonymous function.
• ‘Lambda’ is the keyword used to create such anonymous functions.
Lambda / Anonymous Functions :
Syntax:
lambda Arguments/Parameter: expression
Example 1- WAP for Addition of Two number using lambda function.
z=lambda x,y: x+y
print("Add=",z(10,20))
Output:
Add= 30
Example 2: WAP to find Cube of number using lambda function.
n=int(input("Enter number to find cube of number"))
z=lambda n:n**3
print("Cube=",z(n))
Output:
Enter number to find cube of number 3
Cube= 27
Documentation String :
• In python, programmer can write a documentation for every
function.
• This documentation can be accessed by other functions.
Advantage of Document string
• It is useful when we want to know about any function in
python.
• Programmer can simply print the document string of that
function and can know what that function does.
Documentation String
• Example • Output
def f1(): This is f1 function.
"""This is f1 function.
This function print Hello world on This function print Hello world on
console""" console
print("Hello world!!!")
print(f1.__doc__) Hello world!!!
f1()
Documentation String Example:
Ex-
Sample.py Demo.py
‘‘’Sample file for understanding import Sample
string documentation''' print(help(Sample))
def add(a,b):
''' This is add function
---------------------------------
It takes two arguments a and b and
Output-
store result in c''' Help on module Sample:
c=a+b NAME
print(c) Sample - Sample file for understanding string documentation
FUNCTIONS
add(a, b)
This is add function
It takes two arguments a and b and store result in c FILE
c:\users\jagdish\onedrive\desktop\sample.py
Good Programming practices
• Proper indentation.
• proper naming convention.
• Insert blank line to separate function and classes, and statements
blocks inside functions.
• Whenever required, used comment to explain the code.
• Use document strings that uses the purpose of the function.
• Write non repetitive code.
Introduction to Modules :
• Modules make python programs re-usable.
• Every python code (.py) file can be treated as a module.
• A module can be accessed in other module using import
statement.
• A single module can have multiple functions or classes.
• Each function or class can be accessed separately in import
statement.
Introduction to Modules :
Example Ex- Demo1.py
import Sample
Sample.py Sample.add(10,20)
def add(a,b): Sample.mul(10,20)
c=a+b
print("Addition is",c) Ex- Demo2.py
def mul(a,b): from Sample import add,mul
c=a*b add(3,3)
print("Multipication",c) mul(3,3)
add(10,5)
mul(10,2) Ex- Demo3.py
from Sample import *
add(1,2)
mul(2,2)
Introduction to Modules :
• __pycache__ is a directory that contains bytecode cache files that are
automatically generated by python.
Ex- Reuse of Inbuilt module
from math import pi,sqrt
print("PI=",pi)
print("square_root=",sqrt(9))
-------------------------------------------
Output-
PI= 3.141592653589793
square_root= 3.0
Packages in python
• A packages is a hierarchical file directory structure that has modules and other packages within it.
• Package is nothing but folders/directory.
• In our computer systems, we store our files in organized hierarchies. We don’t store them all in one
location. Likewise, when our programs grow, we divide it into packages.
• In real-life projects, programs are much larger than what we deal with in our journey of learning
Python. A package lets us hold similar modules in one place.
• Like a directory may contain subdirectories and files, a package may contain sub-packages and
modules.
• Packages are collections of modules and packages.
• Package can contain sub packages.
Packages in python
Packages in python
• Creating package:
- Package is folder/directory it contain __init__.py file.
- __init__.py file can be empty, it indicates that the directory it contains
is a Python package, so it is imported the same way a module can be
imported.
- pyc file is created by the Python interpreter when a *. py file is
imported into any other python file. The *. pyc file contains the
“compiled bytecode” of the imported module/program so that the
“translation” from source code to bytecode can be skipped on
subsequent imports of the *. py file.
Packages in python
• Example
Package (Folder)
SubPackage (SubFolder)
FirstModule.py (Module)
def f1():
print(“I am in first Module/ program”)
SecondModule.py (Module)
def f2():
print(“I am in second module/ program”)
Sample.py (Module)
from SubPackage import FirstModule, SecondModule
FirstModule.f1()
SecondModule.f2()
Standard Libraries in Python :
• Modules that are preinstalled in Python are together known as standard library.
• Some useful module in standard library are string, re, datetime, random, os,
multiprocessing, subprocess, socket, email, json, doctest, unittest, argparse, sys.
• We can use this modules for performing task like string parsing, data serialization,
testing, debugging, and manipulating dates, emails, command line arguments etc.
1. Math (import math)
• This is a package for providing various functionalities regarding mathematical
operations.
• Method- import math
dir(math)- written names without any docs
help(math)- It provide documentation
2. Random (import random)
• This is the module which supports various functions for generation of random
numbers and setting seed of random number generator.
Standard Libraries in Python :
Standard Libraries in Python
• os, sys – System & OS operations
• math, random – Math functions & randomness
• datetime – Date & time handling
• json, csv – Data processing
• collections – Advanced data structures
• socket, http – Networking & web
Strings and Operations
Syllabus
Strings and Operations- concatenation, appending,
multiplication and slicing. Strings are immutable, strings
formatting operator, built in string methods and functions.
Slice operation, ord() and chr() functions, in and not in
operators, comparing strings, Iterating strings, the string
module.
Strings :
• The python string data type is a sequence made up of one or more
individual characters, where a character could be a letter, digit,
whitespace, or any other symbols.
• String is continues series of characters delimited by single, double
quotes. triple single quotes, triple double quotes.
• There is a built-in class ‘str’ for handling Python string. You can
prove this with the type() function.
• Ex-
name='India’ # Single line string
name="India“ # Single line string
name='''India''' #Multiline string
name="""India""" #Multiline string
Strings:
Example-
s="Welcome to python"
print("String=",s)
print("Type=",type(s))

-------------------------------------------------
String= Welcome to python
Type= <class 'str'>
Strings :
String Accessing
• We can access each individual character of a string by using index.
• Each character can be accessed in two ways - from the front, or
from the rear end.
• Left to right- Forward index (Positive index)
• Right to left- Backward index (Negative index)
Strings:
mystr="PYTHON"
print("The First character is :",mystr[0])
print("The Third character from :",mystr[-3])

Output :

The First character is : P


The Third character from : H
Escape Sequence or a Back-slash:
• escape sequence or a back-slash will inform the compiler to
simply print whatever you type and not try to compile it.
• You must use one escape sequence for one character. For
example, in order to print 5 double quotes, we will have to use
5 backslashes, one before each quote.
• Python also supports the \n – linefeed and \t – tab sequences.
• EX- Q="what's your name?“- Valid
Q='what's your name?’- Invalid
Q='What\'s your name?’ -Valid
Strings:
print("Five double quotes", "\"\"\"\"\"")
print("Five Single quotes", "\'\'\'\'\'")

Output:
String Concatenation :
• The word concatenate means to join together.
• Concatenation is the operation of joining two strings together.
• Python Strings can join using the concatenation operator +.
Example
str="Python"
str1="Programming"
str2="!!"
str3=str+" "+str1+".."+str2
print(str3)
----------------------------------------------
Python Programming..!!
String appending:
• Append means to add something at the end. In python you can add one string at the end of another string
using the += operator.
• "Concatenate" joins two specific items together, whereas "append" adds another string to existing string.
• Ex- 1
s="Py"
s=s+"thon“ or s+="thon“
----------------------------------------------------
Python
• Ex-2
str="hello:"
name=input("Enter name")
str+=name
print(str)
---------------------------------------------------------
Enter name ABC
hello:ABC
Multiplication or Repetition :
• To write the same text multiple times, multiplication or
repetition is used.
• Multiplication can be done using operator *.
Example-
str= "My Class is Best..."
print(str*3)
------------------------------------------
Output :
My Class is Best…
My Class is Best…
My Class is Best…
String Slicing :
• A substring of a string is called slice.
• Slicing is a string operation.
• Slicing is used to extract a part of any string based on a start index
and end index.
• The extracted portions of Python strings called substrings.
• In slicing colon : is used. An integer value will appear on either
side of colon.
• You can take subset of string from the original string by using []
operators also known as slicing operators.
Syntax :
string_name[Start: Stop: Step]
String Slicing :
Example- Output:
str="Python Programming is very interesting" Characters from 3rd to 6 : thon

print("Characters from 3rd to 6 :",str[2:6]) Characters from 1st to 6 : Python

print("Characters from 1st to 6 :",str[0:6]) Characters from 8th onwards : Programming is very interesting
Characters from 1st onwards : Python Programming is very
print("Characters from 8th onwards :",str[7:]) interesting
print("Characters from 1st onwards :",str[0:]) Last two Characters : ng
print("Last two Characters :",str[-2:]) Characters from Fourth Last onwards : ting
print("Characters from Fourth Last onwards :",str[-4:]) Characters from Fourth Last to Second Last : t
print("Characters from Fourth Last to Second Last :",str[-4:-3]) Reversing Characters of a string : gnitseretni yrev si gnimmargorP
nohtyP
print("Reversing Characters of a string :",str[::-1])
Alternate Characters from 1st to 18th : Pto rgamn
print("Alternate Characters from 1st to 18th :",str[0:17:2])
Strings are immutable
• Immutable- Non-Changeable.
• Whenever you try to modify an existing string variable, a new string is created.
• id() returns the memory address.
• Example-
s="Python"
id(s)
s="Java"
id(s)
----------------------------------------------------------------------
Output-
2375308936240
2375312788528
Note-This means that when you assign a new value to s, a new string object is created rather
than modifying the existing string.
String Formatting
• String formatting is the process of infusing(fill) things in the string
dynamically and presenting the string.
• Formatting with % Operator.
• Formatting with format() string method.
• Formatting with string literals, called f-strings.
• Formatting with String Template Class
String Formatting Operator
• Formatting with % Operator.
• % sign, this string formatting operator is one of the exciting feature in Python.
• The format operator, % allows user to construct strings, replacing parts of strings with the data stored in variables.
• The syntax for the string formatting operator is.
"<Format>" %(<Values>)
Ex-
name= "ABC"
age= 8
print("Name=%s and Age=%d"%(name, age))
print("Name=%s and Age=%d"%('xyz', 10))
-----------------------------------------------------------------------
Name=ABC and Age=8
Name=xyz and Age=10
String Formatting
String Formatting- Example
1. a=‘j’ 6. A=100000
print("a value % c"%a) print("%e"%A)→ 1.000000e+05
2. a=10 7. pi=3
b=20 print("%f"%pi) → 3.000000
print("a value is %d"%a) 8. pi=3.14
print("a value is %i"%a) print("%f"%pi) →3.140000
3. name="abc" 9. 3.140000
print("Name is %s"%name) print("%g"%a) → 3.14
4. a=32768 10. a=10.100000
print("%u"%a) print("%G"%a)→10.1
5. a=10 11. 10.1
print("%o"%a)→12 a=1.000000e+05
print("%x"%a)→a print("%G"%a)→100000
print("%X"%a)→A
String Formatting
• To use two or more argument specifiers, use a tuple (parentheses):
Ex-
name="abc"
age=20
address="xyz, pin 424201“
print("%s\n%d\n%s"%(name, age, address))
----------------------------------------------------------------------
Name=abc
age=20
address=xyz, pin 424201
String Formatters:
• Sometimes, you may want to print variables along with a string.
• You can either use commas, or use string formatters for the
same.
• Ex-
name=input("Enter your name :")
city= "Pune"
country="India"
print("I am",name, "from",city,"\n""I love",country)
-------------------------------------------------------------------------------
Output
Enter your name :ABC
I am ABC from Pune
I love India
String Formatters : Format() method
• The Format() formats the specified values and insert them inside the string
placeholder. The placeholder define using curly bracket {}.
• It has the variables as arguments separated by commas. In the string, use curly
braces to position the variables.
Ex- print("Welcome to {}".format("Python"))
Ex-s1="Hello"
s2="How are you?“
print("Hiii {} {}".format(s1,s2))
print("Hiii {0} {1}".format(s1,s2))
print("Hiii {1} {0}".format(s1,s2))
print("Hiii {}".format(s1,s2))
print("{s2} {s1} How are you?".format(s1="Hii",s2="Hello"))
print("I Like {0}.{1}".format("Python Programming", "Its very interesting"))
print("value of a and b is {a},{b}".format(a=30,b=40))
Formatted String using F-strings
• To create an f-string, prefix the string with the letter “ f ”. The string
itself can be formatted in much the same way that you would with
str.format(). F-strings provide a concise and convenient way to embed
python expressions inside string literals for formatting.
• Ex-
name="abc"
print(f"My name is {name}")
------------------------------------------------------
My name is abc
String Formatters : Template
• This class is used to create a string template for simpler string
substitutions.
Ex-
from string import Template
str=Template('My name is $name and I am from $city studying in $college
College')
str1=str.substitute(name='ABC', city='Pune', college='SKNCOE’)
print(str1)
-----------------------------------------------------------
My name is ABC and I am from Pune and studying in SKNCOE College
built in string methods and functions.

ord() and chr() Functions
• The ord() function returns the ASCII code of the character.
• The chr() function returns character represented by a ASCII number.
• ASCII- A to Z(65-90), a to z(97-122), 0 to 9(48-57)
• ord(character)

EX-
ch='a'
print(ord(ch))
o/p- 97
Ex-
print(chr(97))
o/p- a
in and not in Operators/ Membership
Operator
• in and not in operator can be used • Ex-
with string to determine whether a a="Welcome to python“
string is present in another string.
• Ex- 'b' in 'apple’
if "to" in a:
→ False print("Found")
• Ex- 'b' not in 'apple’ else:
→ True print("Not Found")
• Ex- Ex- 'a' in ‘a’
→ Found
→True
• Ex- Python' in 'Python’
→ True
Comparing String
• Python allows you to compare strings using relational(or comparison)
operators such as ==, != ,>, < , <=, >= etc.
Iterating string
• String is sequence type(Sequence of character), You can iterate through the string using for loop.
• The for loop executes for every character in str. The loop starts with the first character and
automatically ends when the last character is accessed.
EX-
s="Welcome to Python"
for element in s:
print(element,end="")
Ex-
s="Welcome to python"
for i in range(len(s)):
print(s[i])
Ex-
s="Welcome to python"
for i,ele in enumerate(s):
print(i, ele)
Iterating string
• Iterate string using while loop:
Ex-
s="Welcome to Python"
index=0
while index<len(s):
char=(s[index])
print(char,end='')
index=index+1
The String Module
• The String Module Consist of a number of useful constants, classes, and
functions.
• These function are used to manipulate a string.
• It includes predefined strings that can be helpful for various text processing tasks.
• Example-
import string
Print(dir(string))
-----------------------------------------------------------------------------------------------------
['Formatter', 'Template', '_ChainMap', '__all__', '__builtins__', '__cached__', '__doc__',
'__file__', '__loader__', '__name__', '__package__', '__spec__', '_re', '_sentinel_dict', '_string',
'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits',
'printable', 'punctuation', 'whitespace’]
The String Module
• To Know details of particular items.
type(string.digits)
<class 'str’>
• import string
• string.digits
'0123456789’
• import string
string.__builtins__.__doc__
The String Module
Example- Output
import string Digits= 0123456789
print("Digits=",string.digits) Punctuation= !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print("Punctuation=",string.punctuation) Letters=
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQR
print("Letters=",string.ascii_letters) STUVWXYZ
print("Uppercase=",string.ascii_uppercase) Uppercase= ABCDEFGHIJKLMNOPQRSTUVWXYZ
print("Lowercase=",string.ascii_lowercase) Lowercase= abcdefghijklmnopqrstuvwxyz
print("Printable=",string.printable) Printable=
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHI
JKLMNOPQRSTUVWXYZ!"#$%&'()*+,-
./:;<=>?@[\]^_`{|}~
Practical on Unit III
1. Program to concatenate two string using + operator.
2. Program to append a string using += operator.
3. Program to display power of a number without using formatting characters.
4. Program to display power of a number using formatting characters.
5. Program to demonstrate slice operation on string objects.
6. Program to understand how characters in a string are accessed using negative indexes.
7. Program to understand ord() and char() function.
8. Program that uses split() to split a multiline string.
9. Program that counts the occurrences of a character in a string. Do not use built in function.
10. Program to reverse of string by user defined function.
11. Write a python program that accepts a string from user and perform following string
operations- i. Calculate length of string ii. String reversal iii. Equality check of two strings iii.
Check palindrome ii. Check substring

You might also like