0% found this document useful (0 votes)
29 views38 pages

Unit 3 Notes - Functions and Strings

Unit III of the Programming and Problem Solving course covers the importance of functions and strings in programming. It explains the definition and advantages of functions, variable scope, types of parameters, and the use of lambda functions and docstrings. The unit emphasizes code reusability, clarity, and the organization of code for easier maintenance and collaboration.

Uploaded by

indalkarjay
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)
29 views38 pages

Unit 3 Notes - Functions and Strings

Unit III of the Programming and Problem Solving course covers the importance of functions and strings in programming. It explains the definition and advantages of functions, variable scope, types of parameters, and the use of lambda functions and docstrings. The unit emphasizes code reusability, clarity, and the organization of code for easier maintenance and collaboration.

Uploaded by

indalkarjay
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/ 38

Department of First Year Engineering

Programming and Problem Solving


Unit- 3 Notes
-----------------------------------------------------------------------------------
Unit III: Functions and Strings

3.1Need for Functions


Q. Define Function and give its advantages.
Ans:
Function: A function is a block of organized and reusable program code that performs a
single, specific and well-defined task.

Advantages
• Reducing duplication of code
• Decomposing complex problems into simpler pieces
• Improving clarity of the code
• Reuse of code
• Information hiding

Q. Explain the use / need for functions?


Ans:
• Dividing the program into separate well defined functions facilitates each
function to be written and tested separately. This simplifies the process of
program development. Following fig. shows that function A calls other functions
for dividing the entire code into smaller functions.

Fig: Top-down approach of solving a problem

1
• Understanding, coding and testing multiple separate functions are far easier than
doing the same for one huge function.
• If big program has to be developed without the use of any function, then there
will be large number of lines in the code and maintaining that program will be a
big mess.
• All the libraries in Python contains pre-defined and pre-tested functions which the
programmers are free to use directly in their programs without worrying about
their code in detail.
• When a big program is broken into comparatively smaller functions, then
different programmers working on that project can divide the workload by writing
different functions.
• Like Python libraries, programmers can also make their own functions and use
them from different points in the main program or any other program that needs
its functionalities.
• Code Reuse: Code reuse is one of the prominent reason to use functions. Large
programs follow DRY principle i.e. Don’t Repeat Yourself principle. Once a
function is written, it can be called multiple times within the same or by different
program wherever its functionality is needed. Correspondingly, a bad repetitive
code abides by WET principle i.e. Write Everything Twice or We Enjoy Typing.
If a set of instructions have to be executed abruptly from anywhere within the
program code, then instead of writing these instructions everywhere they are
required, a better way is to place these instructions in a function and call that
function wherever required.

3.2Function Definition
Q. What is user defined function? With the help of example illustrate how you can
have such functions in your program.
OR
Q. Explain with example how to define and call a function?
Ans:

How to define function


Function definition consists of a function header that identifies the function, followed by the
body of the function containing the executable code for that function.

User Defined Function


The user defined functions, are functions created by users in their programs using def
keyword.

2
To define user defined function following points must be considered:
• Function blocks start with the keyword def
• The keyword is followed by the function name and parenthesis ( ) . The function
name is uniquely identifying the function.
• After the parenthesis a colon (:) is placed
• Parameters or arguments that function accepts are placed within parenthesis.
They are optional.
• The first statement of a function can be n optional statement-the documentation
string of the function or docstring describe what the function does.
• The code block within the function is properly indented to form the block code.
• A function may have a return[expression] statement. It is optional.

A function definition comprises two parts:


• Function header
• Function body

Syntax:
def function_name(variable1, variable2,..): Function Header
Documentation string
Statement block
return [expression] Function Boy

How to call a function


• The function call statements invoke the function. When a function is invoked, the program
control jumps to the called function to execute the statements that are part of that function.
• Once the called function is executed, the program control passes back to calling function.

Syntax of calling function:


function_name()

• Function call statement has the following syntax when it accepts parameters

function_name(variable1, variable2,..)

# Program that subtract two numbers using function


def diff(x, y): #function to subtract two numbers
return x-y
a=20
b=10
print(diff(a,b)) #function call

3
OUTPUT
10

3.3 Variable Scope and Lifetime


Q. Explain variable scope and lifetime.
Ans:
• Scope of the variable is the part of the program in which the variable is accessible.
• Lifetime of a variable is the period throughout which the variable exists in the
memory.
3.3.1 Local and Global variables:
• Local variables:
o Parameters and variables defined inside a function are not accessible from
outside. Hence, they have a local scope.
o The lifetime of variables inside a function is as long as the function executes.
o They are destroyed once we return from the function. Hence a function does
not remember the value of a variable from its previous calls.
• Global Variables:
o The variables which are defined in the main body of the program file.
Outside any function. Are called as global variables.
o They are visible throughout the program.
• Here is an example to illustrate the scope of a variable inside a function.
def var_scope():
x=5 # Here x is local variable
print(“Value inside function:”,x)
x=10 #Here x is Global variable
var_scope()
print(“value outside function:”, x)
Output:
Value inside function: 5
Value outside function: 10

4
• In this example, we can observe that the value of x is 10 initially.
• Then the var_scope() function is called, it has the value of x as 5, but it is only inside
the function.
• It did not affect the value outside the function.
• This happens since the variable x inside the function var_scope() is considered as
different (local to the function) from the one outside.
• Although they have same names, they are two different variables with different
scope.

Q. Differentiate between global and local variables


Ans:
Global variables Local variables
1. They are defined in the main body of the 1. They are defined within a function and is
program file local to that function.
2. They can be accessed throughout the 2. They can be accessed from the point of its
program file definition until the end of the block in which
it is defined

3.Scope of global variables is Throughout 3.Scope of local variables is Within a


the program. function, inside which they are declared.
4.Life of global variables: Remain in 4.Life of local variables: Created when the
existence for the entire time your program is function block is entered and destroyed upon
executing. exit.

3.3.2 Using the global statement:


• To define a variable defined inside a function as a global, you must use the global
statement.
• This declares the local or the inner variable of the function to have module scope.

5
• For ex.
x=”Good”
def show()
global y
y = “Morning”
print(“In function x is – “, x)

show()
print(“Outside function y is – “, y) # accessible as it is global variable
print(“ x is – “, x)

Output:
In function x is- Good
Outside function y is – Morning
x is - Good

3.3.3 Resolution of Names


Q. When we can have variable with same name as that of global variable in program,
how is name resolved in python.

Ans:
• If we have variable with same name as Global and Local variable. Then local
variable is accessible within the function/block in which it is defined.
• Global variable is defined outside of any function and accessible throughout the
program.
• In the code given below, str is a global string because it has been defined before
calling the function.
• Program that demonstrates using a variable defined in global namespace.

6
def fun():
print(str)
str = “Hello World!!!”
fun()

Output:
Hello World

• You cannot define a local variable with the same name as that of global variable. If
you want to do that you just use the global statement.
• Program describes using a local variable with same name as that of global
def f():
global str
print(str)
str= “hello world”
print(str)

str= “ welcome to python programming”


f()
Output:
welcome to python programming
hello world

3.4 The return statement


Q. Return statement is optional. Justify this statement with the help of example.
Ans:
• In python, every function is expected to have return statement.
• When we do not specify return statement at the end of our function, Implicit return
statement is used as last statement for such function.
• This implicit return statement returns nothing to its caller, so it is said to return none.

7
• In the example below we can see there is no return statement used.
• So here default return none is used as last statement, and program will execute
successfully.
def func1():
x=5
print(“Value of x: ”,x)
func1()
print(“Hello World!)

Output:
Value of x: 5
Hello World

• So from this we can say that return statement is optional in function definition.
Q. Write a note on return statement with suitable example.
Ans:
• In python, every function is expected to have return statement.
• When we do not specify return statement at the end of our function, Implicit return
statement is used as last statement for such function.
• This implicit return statement returns nothing to its caller, so it is said to return none.
• But you can change this default behavior by explicitly using the return statement to
return some value to the caller.

• The syntax of return statement is:


return [expression]
• a return statement with no argument is same as return none
• A function may or may not return a value.
• The return statement is used for two things:
1. Return a value to the caller
2. To end and exit a function and go back to its caller
• Example 1: program to write a function without a return statement and try to print its
return value. Such function should return none.
8
def display(str):
print(str)
x= display(“Hello World”)
print(x)
print(display(“Hello again”))
Output:
Hello World
None
Hello again
None

Note that in output None is return by the function


Example 2: Program for function which returns integer value to the caller.
def cube(x):
return (x*x*x)
num = 10
result= cube(num)
print(“Cube of “, num, ”=”, result)

Output:
Cube of 10 = 100
Note: return statement cannot be used outside the function.

3.5 Types of Parameters


Q. Explain types of function arguments. OR
Q. Write a note on:
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments

9
Ans: There are four types of function arguments available in Python as follow:
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
1. Required Arguments:
• In the required arguments, the arguments are passed to the function in correct
positional order.
• The number of arguments in the function call should exactly match with the
number of arguments specified in the function definition
• For ex.
def person(name, age):
print(name)
print( age)
person(“Amar”, 20)
Output:
Amar
20

2. Keyword Arguments:
• In keyword arguments the order(or position) of the arguments can be changed.
• The values are assigned to the arguments by using their names
• The python interpreter uses keywords provided in the function call to match the
values with parameters.
• Program to demonstrate keyword arguments
def person(name, age, salary):
print(“Name: ”, name)
print(“Age: ”, age)
print(“Salary: ”, salary)

person(salary=50000, name=”Ajay”, age=30)

10
Output:
Name: Ajay
Age: 30
Salary: 50000

• Note:
o All the keyword arguments passed should match one of the arguments
accepted by the function
o The order of keyword argument is not important
o In no case argument should receive a value more than once

3. Default Arguments:
• Python allows user to specify function arguments that can have default
values
• Function call can have less number of arguments than provided in its
definition.
• User can specify default value for one or more arguments which is used if no
value provided in call for that argument.
def display(name, age=18):
print(“Name: ”+ name)
print(“Age: ”, age)

display(age=25, name=”Ajay”)
display(”Amar”)
Output:
Name: Ajay
Course: 25
Name: Amar
Course: 18

• In the above example, default value is not specified for name, so it is mandatory.

11
• But age has provided default value, so if value not provided in calling for age, it will
take 18.
Note: Non default arguments should be provided before default arguments.

4. Variable Length arguments:


• In some situations, it is not known in advance how many arguments will be
passed to a function.
• I such cases variable length arguments can be used, in this function definition
uses an asterisk(*) before the parameter name.
Syntax:
def function_name([arg1, arg2, …] *var_args_tuple )
function statements
return [expression]
Program to demonstrate the use of variable length arguments
def sumFun(a, *tup):
sum1=a
for i in tup:
sum1= sum1 + i
print(sum1)
sumFun(10, 20, 30, 40)
Output:
100

• In the above program, in the function definition we have two parameters- one is a
and other is variable length parameter tup.
• The first value is assigned to a and other values are assigned to parameter tup.
• In tup parameter, 0 to n values are acceptable.
• The variable length argument if present in the function definition should be the last
in the list of formal parameters.
• To see or use all the values in the variable length parameter, we have to use for loop
as given in above example.

12
3.6 Lambda or Anonymous functions
Q. What is lambda or anonymous functions in python? Explain with example.
Ans.
• Lambda or anonymous function have no name.
• They are created using lambda keyword instead of def.
• Lambda function contains only single line.
• Lambda function can take any number of arguments.
• It can returns only one value in the form of an expression.
• Lambda function does not have explicit return statement.
• Lambda function cannot contain multiline expressions.
• It cannot access variable other than those in their parameter list
• We can pass Lambda function as arguments in other functions.
• Syntax:
Lambda arguments: expression

▪ The arguments contains comma separated list of variables


▪ The expression is an arithmetic expressions that uses these arguments
• Example:
sum = lambda x, y: x + y
print(“sum =”, sum(3,5))

Output:
Sum=8

13
3.7 Documentation String
Q. What are docstring?
Ans:
• Docstrings (documentation string) serves the same purpose as that of comments.
• Docstrings are designed to explain code.
• Docstrings are created by putting multiline string to explain the code.
• Docstrings are important as they help tools to automatically generate printed
documentation
• Docstrings are very helpful to readers and users of the code to interactively browse
the code.
• Docstrings specified in function can be accessed through the doc attributes of
the functions.
• Unlike comments, Docstrings are retained throughout the runtime of the program.
(Docstrings ignored by the compilers)
• Syntax:
def function_name(parameters):
""" Function written for factorial,
Calculates factorial of number """
Function statements
return [expression]
• Example:
def func():
""" function just prints message.
It will display Hello World !! """
print(“Hello World!!”)
func( )
print(func. doc )
Output:
Hello World!!
function just prints message.
It will display Hello World !!

14
3.8 Good Programming Practices
Q. Write a note on good programming practices in python.
Ans:
To develop readable, effective and efficient code programmer has to take care of following
practices:
• Instead of tabs, use 4 spaces for indentations.
• Wherever required use comments to explain code.
• Use space around operators and after commas.
• Name of the function should be in lower case with underscore to separate words
Eg. get_data()
• Use document string that explains purpose of the functions
• Name of the class should be written as first letter capital in each word
Eg. ClassName()
• Do not use non ASCII character in function names or any other identifier.
• Inserts blank lines to separate functions, Classes, and statement blocks inside
functions

3.9 Introduction to Module


Q. What are modules? How do you use them in your program?
Ans:
Module:
• Definition: Module is a file with .py extension that has definitions of functions and
variables that can be used even in other programs.
• Modules are the pre-written pieces of code.
• They are used to perform common tasks like generate random numbers, performing
mathematical operations etc.
• Using Modules in programs:
o Programs in which you want to use functions or variables defined in the module will
simply import that particular module (or .py file).

15
o To use a module in any program, add import module_name as the first line in your
program.
Syntax:
import module_name

o Then module_name.var is written to access functions and values with the name var
in the module.

o Example: Program to print sys.path variable


import sys
print("PYTHONPATH = \n", sys.path)

o Here, sys standard library module is imported.


o When import sys statement is executed, python looks for sys.py module and then
executes the statement to print sys.path variable.

• Module Loading & Execution (optional)


o A module imported in a program must be located and loaded into memory
before it can be used.
o Python will search a module:
▪ in current working directory
▪ if not found there, it searches directories in the environmental
variable PYTHONPATH.
▪ If not found, then a Python installation specific path (like
C:\Python34\Lib) is searched.
▪ If the module is not located even there, then an error ImportError
exception is generated.
o In order to make a module available to other programs, it should be either
saved in the directory specified in path PYTHONPATH, or stored in Python
installation Lib directory.
o Once a module is located, it is loaded in memory.

16
o A compiled version of module with file extension .pyc is generated.
o Next time when the module is imported, this .pyc file is loaded instead of .py
file.
o A new compiled version of a module is again produced whenever the
compiled module is out of date.
o Even the programmer can force the python shell to reload and recompile
the .py file to generate a new .pyc file by using reload( ) function.

3.9.1 The from…import statement


• A module may contain definition for many variables or functions.
• When a module is imported, any variable or function defined in that module can be
used.
• But if you want to use only selected variables or functions, then use the
from…import statement.
• Syntax
from module_name import member_name
• Example:
from math import pi
print("PI= ",pi)

• To import more than one item from a module, use comma separated list. For
example, to import value of pi and sqrt( ) from math module write:
Example:
from math import pi, sqrt
print("PI= ", pi)
print("Square root of 4=", sqrt(4))
Output:
PI= 3.141592653589793
Square root of 4= 2.0

17
• To import all identifiers defined in a module, except those beginning with
underscore ( _ ), use import * statement.
• Example:
from math import *
print("PI= ", pi)
print("Square root of 4=", sqrt(4))
Output:
PI= 3.141592653589793
Square root of 4= 2.0

3.9.2 Name of Module


• Every module has a name.
• You can find the name of a module by using the name attribute of the module.
• Example:
print("Hello")
print("Name of module is = ", name )
Output:
Hello
Name of module is = main
• Note that, for every standalone program written by the user the name of module is
main .

3.9.3 Making your own module


• You can create your own modules.
• Every python program is a module.
• That is, every file that is saved with .py extension is a module.
• For example, let us create our own module say Mymodule.py
• In this file, some functionality is written.
File Name: Mymodule.py
def display():
print("Hello")
18
str = "Welcome to World of Python"

• Then open another file (main.py) and write code given below.
File Name: main.py
import Mymodule
print("Mymodule string=", Mymodule.str)
Mymodule.display()

• When you run main.py file, you get following output.


Mymodule string= Welcome to World of Python
Hello

• Modules should be placed in the same directory as that of the program in which it is
imported.
• It can also be stored in one of the directories listed in sys.path.
• The dot operator is used to access members (variables or functions) of module.

3.10 Packages
Q. What are packages in python?
Ans:
• A package is a hierarchical file directory structure.
• A package has modules and other packages within it.
• Every package in python is a directory which must have a special file called
init .py. This may not even have a single line of code.
• It is simply added to indicate that this is not an ordinary directory and contains a
Python package.
• A package can be accessed in other python program using import statement.
• For example, to create a package MyPackage, create directory called MyPackage
having module MyModule and init .py file.
File Name: Mymodule.py
def display():

19
print("Hello")
str = "Welcome to World of Python"
• Now, to use MyModule in a program, import it in any one of the two ways:

import MyPackage.MyModule
or
from MyPackage import MyModule

3.11Introduction to Standard Library Modules


Q. Explain any four standard library modules.
Ans:
• Modules that are pre-installed in python together are known as the standard library.
• A few standard libraries in python are:
1. Math (import math)
This is a package for providing various functionalities regarding mathematical
operations.
For ex. math.sqrt(9), will give you 3 as square root of 9.
2. Random (import random)
This is a module which supports various functions for generation of random
numbers and setting seed of random number generator.
For ex. random.random(), function will generate random number
3. Sys (import sys)
It supports all system information related operations.
For ex. sys.path , will give you information about Current file Path.
4. Os ( import os )
It gives all the information related to Operating System.
For ex. os.name , will give you the name of Operating System.

20
Strings
4.1 Strings and Operations

Q 1. What is String? With the help of example explain how we can create string
variable in python.
Ans:
• Strings data type is sequence of characters, where characters could be letter, digit,
whitespace or any other symbol.
a. Creation of Strings:
o Strings in Python can be created using single quotes or double quotes or even
triple quotes.
o Example:
string1 = 'Welcome' # Creating a String with single Quotes
string2 = "Welcome" # Creating a String with double Quotes
string3 = '''Welcome''' # Creating a String with Triple Quotes

b. Accessing strings:
o In Python, individual characters of a String can be accessed by using the method
of Indexing or range slice method [:].
o Indexing allows negative address references to access characters from the back
of the String, e.g. -1 refers to the last character, -2 refers to the second last
character and so on.

String W E L C O M E
Indexing 0 1 2 3 4 5 6
Negative Index -7 -6 -5 -4 -3 -2 -1

1
PPS Unit-VI RMD Warje

o Example:
string = 'Welcome'
print(string[0]) #Accessing string with index
print(string[1])
print(string[2])
print(string[0:2]) #Accessing string with range slice method

Output:
w
e
l
we

c. Deleting/Updating from a String:


o In Python, updating or deletion of characters from a String is not allowed as
Strings are immutable.
o Although deletion of entire String is possible with the use of a built-in del
keyword.
o Example:
string='welcome'
del string

Q 2. Explain Operations on string.


Ans:
Operation Description Example Output
Concatenation(+) -It joins two strings x="Good" Good Morning
and returns new list. y="Morning"
z=x+y
print(z)

2
Append (+=) -Append operation x="Good" Good Morning
adds one string at y="Morning"
the end of another x+=y
string print(x)
Repetition(*) -It repeats elements x="Hello" HelloHello
from the strings n y=x*2
number of times print(y)
Slice [] - It will give you x="Hello" e
character from a print(x[1])
specified index.

Range slice[:] -It will give you x="Hello" He


characters from print(x[0:2])
specified range slice.

4.2 Strings are immutable


Q 3. Python strings are immutable. Comment on this.
Ans:
• Python Strings are immutable, which means that once it is created it cannot be changed.
• Whenever you try to change/modify an existing string, a new string is created.
• As every object (variable) is stored at some address in computer memory.
• The id() function is available in python which returns the address of object(variable) in
memory. With the help of memory locations/address we can see that for every
modification, string get new address in memory.
• Here is the example to demonstration the address change of string after modification.
# prints string1 and its address
string1="Good"
print("String1 value is: ",string1)
print("Address of string1 is:",id(string1))

3
# prints string2 and its address
string2="Morning"
print("String2 value is: ",string2)
print("Address of string2 is: ",id(string2))

#appending string1 to string2


string1+= string2
print("String1 value is: ",string1)
print("Address of string1 is:",id(string1))

Output:
String1 value is: Good
Address of String1 is: 1000

String2 value is: Morning


Address of String1 is: 2000

String1 value is: GoodMorning


Address of String1 is: 3000

• From the above output you can see string1 has address 1000 before modification. In
later output you can see that string1 has new address 3000 after modification.
• It is very clear that, after some operations on a string new string get created and it has
new memory location. This is because strings are unchangeable/ immutable in nature.
Modifications are not allowed on string but new string can be created at new address
by adding/appending new string.

4.3 Strings formatting operator


Q 4. Explain various ways of string formatting with example.
Ans:
• In python, % sign is a string formatting operator.

4
• The % operator takes a format string on the left and the corresponding values in a
tuple on the right.
• The format operator, % allows users to replace parts of string with the data stored in
variables.
• The syntax for string formatting operation is:
"<format>" % (<values>)
• The statement begins with a format string consisting of a sequence of characters and
conversion specification.
• Following the format string is a % sign and then a set of values, one per conversion
specification, separated by commas and enclosed in parenthesis.
• If there is single value then parenthesis is optional.
• Following is the list of format characters used for printing different types of data:
Format Purpose
Symbol
%c Character
%d or %i Signed decimal integer
%s String

%u Unsigned decimal integer

%o Octal integer

%x or %X Hexadecimal integer

%e or %E Exponential notation

%f Floating point number

%g or %G Short numbers in floating point or exponential notation

Example: Program to use format sequences while printing a string.


name="Amar"
age=8
print("Name = %s and Age = %d" %(name,age))
print("Name = %s and Age = %d" %("Ajit",6))

5
Output:
Name = Amar and Age = 8
Name = Ajit and Age = 6

In the output, we can see that %s has been replaced by a string and %d has been replaced by
an integer value.

4.4 Built-in String methods and functions


Q 5. List and explain any 5 string methods.
Or
Q. Explain the use of ( ) with the help of an example.
Ans.
Sr. Function Usage Example
No.
1 capitalize() This function is used to capitalize str="hello"
first letter of string. print(str.capitalize())
output:
Hello
2 isalnum() Returns true if string has at least 1 message="JamesBond007"
character and every character is print(message.isalnum())
either a number or an alphabet and output:
False otherwise. True
3 isalpha() Returns true if string has at least 1 message="JamesBond007"
character and every character is an print(message.isalpha())
alphabet and False otherwise. output:
False
4 isdigit() Returns true if string has at least 1 message="007"
character and every character is a print(message.isdigit())
digit and False otherwise. output:
True
5 islower() Returns true if string has at least 1 message="Hello"

6
character and every character is a print(message.islower())
lowercase alphabet and False output:
otherwise. False
6 isspace() Returns true if string contains only message=" "
white space character and False print(message.isspace())
otherwise. output:
True
7 isupper() Returns true if string has at least 1 message="HELLO"
character and every character is an print(message.isupper())
uppercase alphabet and False output:
otherwise. True
8 len(string) Returns length of the string. str="Hello"
print(len(str))
output:
5
9 zfill(width) Returns string left padded with str="1234"
zeros to a total of width characters. print(str.zfill(10))
It is used with numbers and also output:
retains its sign (+ or -). 0000001234
10 lower() Converts all characters in the string str="Hello"
into lowercase. print(str.lower())
output:
hello
11 upper() Converts all characters in the string str="Hello"
into uppercase. print(str.upper())
output:
HELLO
12 lstrip() Removes all leading white space in str=" Hello"
string. print(str.lstrip())
output:
Hello

7
13 rstrip() Removes all trailing white space in str=" Hello "
string. print(str.rstrip())
output:
Hello
14 strip() Removes all leading white space str=" Hello "
and trailing white space in string. print(str.strip())
output:
Hello
15 max(str) Returns the highest alphabetical str="hello friendz"
character (having highest ASCII print(max(str))
value) from the string str. output:
z
16 min(str) Returns the lowest alphabetical str="hellofriendz"
character (having lowest ASCII print(min(str))
value) from the string str. output:
d
17 replace(old,new[, max]) Replaces all or max (if given) str="hello hello hello"
occurrences of old in string with print(str.replace("he","Fo"))
new. output:
Follo Follo Follo
18 title() Returns string in title case. str="The world is beautiful"
print(str.title())
output:
The World Is Beautiful
19 swapcase() Toggles the case of every character str="The World Is
(uppercase character becomes Beautiful"
lowercase and vice versa). print(str.swapcase())
output:
tHE wORLD iS
bEAUTIFUL
20 split(delim) Returns a list of substrings str="abc,def, ghi,jkl"

8
separated by the specified print(str.split(','))
delimiter. If no delimiter is output:
specified then by default it splits ['abc', 'def', ' ghi', 'jkl']
strings on all whitespace
characters.
21 join(list It is just the opposite of split. The print('-'.join(['abc', 'def', '
function joins a list of strings using ghi', 'jkl']))
delimiter with which the function output:
is invoked. abc-def- ghi-jkl
22 isidentifier() Returns true if the string is a valid str="Hello"
identifier. print(str.isidentifier())
output:
True
23 enumerate(str) Returns an enumerate object that str="Hello World"
lists the index and value of all the print(list(enumerate(str)))
characters in the string as pairs. output:
[(0, 'H'), (1, 'e'), (2, 'l'), (3,
'l'), (4, 'o'), (5, ' '), (6, 'W'),
(7, 'o'), (8, 'r'), (9, 'l'), (10,
'd')]

4.5Slice operation
Q 6. What is slice operation? Explain with example.
Ans.
Slice: A substring of a string is called a slice.
A slice operation is used to refer to sub-parts of sequences and strings.
Slicing Operator: A subset of a string from the original string by using [] operator
known as Slicing Operator.

9
Indices in a String

Index from
P Y T H O N
the start
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1

Index from
Syntax:
the end
string_name[start:end]
where start- beginning index of substring
end -1 is the index of last character

Program to demonstrate slice operation on string objects


str=”PYTHON”
print(“str[1:5]= “, str[1:5]) #characters start at index 1 and extending upto index 4
# but not including index 5
print(“str[ :6]= “, str[ :6]) # By defaults indices start at index 0
print(“str[1: ]= “, str[1: ]) # By defaults indices ends upto last index
print(“str[ : ]= “, str[ : ]) # By defaults indices start at index 0 and end upto last
#character in the string
#negative index
print(“str[-1]= “, str[ -1]) # -1 indicates last character
print(“str[ :-2 ]= “, str[ : -2]) #all characters upto -3
print(“str[ -2: ]= “, str[ -2: ]) #characters from index -2
print(“str[-5 :-2 ]= “, str[ -5: -2]) # characters from index -5 upto character index -3

OUTPUT
str[1:5]= YTHO
str[ :6]= PYTHON
str[1: ]= YTHON
str[ : ]= PYTHON

10
str[-1]= N
str[ :-2 ]= PYTH
str[ -2: ]= ON
str[-5 :-2 ]= YTH

Specifying Stride while Slicing Strings


• In the slice operation, you can specify a third argument as the stride, which refers
to the number of characters to move forward after the first character is retrieved
from the string.
• The default value of stride is 1, i.e. where value of stride is not specified, its
default value of 1 is used which means that every character between two index
number is retrieved.
Program to use slice operation with stride
str=” Welcome to the world of Python“
print(“str[ 2: 10]= “, str[2:10]) #default stride is 1
print(“str[ 2:10:1 ]= “, str[2:10:1]) #same as stride=1
print(“str[ 2:10:2 ]= “, str[2:10:2]) #skips every alternate character
print(“str[ 2:10:4 ]= “, str[2:10:4]) #skips every fourth character

OUTPUT
str[ 2: 10]=lcome to
str[ 2: 10]= lcome to
str[ 2:10:2 ]=loet
str[ 2:10:4 ]=l
• Whitespace characters are skipped as they are also part of the string.

4.6ord() and chr() functions
Q 7.Write a short note on ord() and chr() functions
Ans.
• The ord() function return the ASCII code of the character

11
• The chr() function returns character represented by a ASCII number.

ch=’R’ print(chr(82)) print(chr(112)) print(ord(‘p’))


print(ord(ch))

OUTPUT OUTPUT OUTPUT OUTPUT


82 R p 112

4.7 in and not in operators


Q 8.Write a short note on in and not in operators
OR
Q.With the help of example, explain significance of membership operators.
Ans.
• in and not in operators can be used with strings to determine whether a string is
present in another string. Therefore the in and not in operator is known as
membership operators.

• For example:
str1=” Welcome to the world of Python!!!“ str1=” This is very good book“
str2=”the” str2=”best”
if str2 in str1: if str2 in str1:
print(“found”) print(“found”)
else: else:
print(“Not found”) print(“Not found”)

OUTPUT OUTPUT
Found Not found

• You can also use in and not in operators to check whether a character is present in a
word.
• For example:
‘u‘ in “starts” ‘v‘ not in “success”

12
OUTPUT OUTPUT
False True

4.8 Comparing strings


Q 9. Explain string comparison operator with example?
Ans.
➢ Python allows us to combine strings using relational (or comparison) operators such
as >, <, <=,>=, etc.
➢ Some of these operators along with their description and usage are given as follows:
Operator Description Example
== If two strings are equal, it returns True. >>>”AbC”==”AbC”
True
!= or <> If two strings are not equal, it returns True. >>>”AbC”!=”Abc”
True
> If the first string is greater than the second, it >>>”abc”>”Abc”
returns True. True
< If the second string is greater than the first, it >>>”abC”<”abc”
returns True. True
>= If the first string is greater than or equal to >>>”aBC”>=””ABC”
the second, it returns True. True
<= If the second string is greater than or equal to >>>”ABc”<=”ABc”
the first, it returns True. True

➢ These operators compare the strings by using ASCII value of the characters.
➢ The ASCII values of A-Z are 65-90 and ASCII code for a-z is 97-122.
➢ For example, book is greater than Book because the ASCII value of ‘b’ is 98 and ‘B’
is 66.

String Comparison Programming Examples: (Any one)


➢ There are different ways of comparing two strings in Python programs:

13
➢ Using the ==(equal to) operator for comparing two strings:
• If we simply require comparing the values of two variables then you may use
the ‘==’ operator.
• If strings are same, it evaluates to True, otherwise False.

• Example1:
first_str='Kunal works at Phoenix'
second_str='Kunal works at Phoenix'
print("First String:", first_str)
print("Second String:", second_str)
#comparing by ==
if first_str==second_str:
print("Both Strings are Same")
else:
print("Both Strings are Different")

Output:
First String: Kunal works at Phoenix
Second String: Kunal works at Phoenix
Both Strings are Same

• Example2(Checking Case Sensitivity):


first_str='Kunal works at PHOENIX'
second_str='Kunal works at Phoenix'
print("First String:", first_str)
print("Second String:", second_str)
#comparing by ==
if first_str==second_str:
print("Both Strings are Same")
else:
print("Both Strings are Different")

14
Output:
First String: Kunal works at PHOENIX
Second String: Kunal works at Phoenix
Both Strings are Different

➢ Using the !=(not equal to) operator for comparing two strings:
• The != operator works exactly opposite to ==, that is it returns true is both
the strings are not equal.
• Example:
first_str='Kunal works at Phoenix'
second_str='Kunal works at Phoenix'
print("First String:", first_str)
print("Second String:", second_str)
#comparing by !=
if first_str!=second_str:
print("Both Strings are Different")
else:
print("Both Strings are Same")
output:
First String: Kunal works at Phoenix
Second String: Kunal works at Phoenix
Both Strings are Same

➢ Using the is operator for comparing two strings:


• The is operator compares two variables based on the object id and returns
True if the two variables refer to the same object.
• Example:
name1=”Kunal”
name2=”Shreya”
print(“name1:”,name1)

15
print(“name2:”,name2)
print(“Both are same”,name1 is name2)
name2=”Kunal”
print(“name1:”,name1)
print(“name2:”,name2)
print(“Both are same”,name1 is name2)
• Output:
name1=Kunal
name2=Shreya
Both are same False
name1=Kunal
name2=Kunal
Both are same True
• In the above example, name2 gets the value of Kunal and subsequently
name1 and name2 refer to the same object.

4.9 Iterating strings
Q. No.10 How to iterate a string using:
Ans.
i) for loop with example
ii) while loop with example
Ans.

➢ String is a sequence type (sequence of characters).


➢ We can iterate through the string using:

i) for loop:
• for loop executes for every character in str.
• The loop starts with the first character and automatically ends when
the last character is accessed.
• Example-

16
str=”Welcome to python”
for i in str:
print(i,end=’ ’)
Output-
We lco me to Pyt hon

ii) while loop:


• We can also iterate through the string using while loop by writing the
following code.
• Example-
message=” Welcome to python”
index=0
while index < len(message):
letter=message[index]
print(letter,end=’ ‘)
index=index+1
Output-
We lco me to Pyt hon

• In the above program the loop traverses the string and displays each
letter.
• The loop condition is index < len(message), so the moment index
becomes equal to the length of the string, the condition evaluates to
False, and the body of the loop is not executed.
• Index of the last character is len(message)-1.

4.10 The string module


Q. No. 11 Write a note on string module?
➢ The string module consists of a number of useful constants, classes and functions.
➢ These functions are used to manipulate strings.

17
➢ String Constants: Some constants defined in the string module are:
• string.ascii_letters: Combination of ascii_lowecase and ascii_uppercase
constants.
• string.ascii_lowercase: Refers to all lowercase letters from a-z.
• string.ascii_uppercase: Refers to all uppercase letters from A-Z.
• string.lowercase: A string that has all the characters that are considered
lowercase letters.
• string.uppercase: A string that has all the characters that are considered
uppercase letters.
• string.digits:Refers to digits from 0-9.
• string.hexdigits: Refers to hexadecimal digits,0-9,a-f, and A-F.
• string.octdigits: Refers to octal digits from 0-7.
• string.punctuation: String of ASCII characters that are considered to be
punctuation characters.
• string.printable: String of printable characters which includes digits, letters,
punctuation, and whitespaces.
• string.whitespace: A string that has all characters that are considered
whitespaces like space, tab, return, and vertical tab.
➢ Example: (Program that uses different methods such as upper, lower, split, join,
count, replace, and find on string object)
str=”Welcome to the world of Python”
print(“Uppercase-“, str.upper())
print(“Lowercase-“, str.lower())
print(“Split-“, str.split())
print(“Join-“, ‘-‘.join(str.split()))
print(“Replace-“,str.replace(“Python”,”Java”))
print(“Count of o-“, str.count(‘o’))
print(“Find of-“,str.find(“of”))

18

You might also like