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

Unit 2 Functions Strings

The document provides an overview of functions in Python, including their definition, syntax, and how to call them. It covers various types of function arguments, such as required, keyword, default, and variable-length arguments, as well as the use of lambda functions and built-in functions like map(), filter(), and reduce(). Additionally, it discusses variable scope, including global, local, and nonlocal variables, and introduces recursive functions and type conversion methods.

Uploaded by

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

Unit 2 Functions Strings

The document provides an overview of functions in Python, including their definition, syntax, and how to call them. It covers various types of function arguments, such as required, keyword, default, and variable-length arguments, as well as the use of lambda functions and built-in functions like map(), filter(), and reduce(). Additionally, it discusses variable scope, including global, local, and nonlocal variables, and introduces recursive functions and type conversion methods.

Uploaded by

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

Functions

!A block of organized, reusable code that is used to


perform a single, related action.
! Provides better modularity for your application and a high
degree of code reusing.
! Python gives you many built-in functions like print(), etc.
but you can also create your own functions. These
functions are called user-defined functions.
Defining a Function
! You can define functions to provide the required functionality.
Here are simple rules to define a function in Python.
! Function blocks begin with the keyword def followed by the function
name and parentheses ( ( ) ).
! Any input parameters or arguments should be placed within these
parentheses. You can also define parameters inside these
parentheses.
! The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
! The code block within every function starts with a colon (:) and is
indented.
! The statement return [expression] exits a function, optionally passing
back an expression to the caller. A return statement with no
arguments is the same as return None.
Syntax & Example
! def functionname( parameters ):
"function_docstring“
function_suite
return [expression]
! def printme( str ):
"This prints a passed string into this function”
print (str)
return
Calling a Function

! Defining a function gives it a name, specifies the


parameters that are to be included in the function and
structures the blocks of code.
! Once the basic structure of a function is finalized, you can
execute it by calling it from another function or directly
from the Python prompt.
!# Function definition is here
! def printme( str ):
"This prints a passed string into this function“
print (str)
return
! # Now you can call printme function
! printme("This is first call to the user defined function!")
! printme("Again second call to the same function")
! Output:-

This is first call to the user defined function!


Again second call to the same function
Pass by Reference vs Value

! Allparameters (arguments) in the Python language are


passed by reference.
! Means if you change what a parameter refers to within a
function, the change also reflects back in the calling
function.
! Example 1:-
! def changeme( mylist ):
"This changes a passed list into this function"
print ("Values inside the function before change: ", mylist)
mylist[2]=50
print ("Values inside the function after change: ", mylist)
return
! mylist = [10,20,30]
! changeme( mylist )
! print ("Values outside the function: ", mylist)
! Output:-

Values inside the function before change: [10, 20, 30]


Values inside the function after change: [10, 20, 50]
Values outside the function: [10, 20, 50]
! Example 2:-
! def changeme( mylist ):

"This changes a passed list into this function"


mylist = [1,2,3,4] # This would assi new reference in mylist
print ("Values inside the function: ", mylist)
return
! mylist = [10,20,30]
! changeme( mylist )
! print ("Values outside the function: ", mylist)
! Output:-

Values inside the function: [1, 2, 3, 4]


Values outside the function: [10, 20, 30]
Function Arguments

! Youcan call a function by using the following types of


formal arguments −
! Required arguments
! Keyword arguments
! Default arguments
! Variable-length arguments
Required Arguments/ Positional Arguments
! Required arguments are the arguments passed to a
function in correct positional order.
! Here, the number of arguments in the function call should
match exactly with the function definition.
! Example:-
! def printme( str ):
"This prints a passed string into this function"
print (str)
return
! printme()
! Output:-

Traceback (most recent call last):


File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
Sum of Two Number
! def sum(a,b):
return (a+b)
def mul(a,b):
return (a*b)
s = sum(10,20)
print("Sum is",s)
M=mul(10,30)
Print(“Multiplication”,M)
Output:
Sum is 30
Keyword Arguments

! Keyword arguments are related to the function calls.


! When you use keyword arguments in a function call, the
caller identifies the arguments by the parameter name.
! This allows you to skip arguments or place them out of
order because the Python interpreter is able to use the
keywords provided to match the values with parameters.
! Example:-
! def printme( str ):
"This prints a passed string into this function"
print (str)
return
! printme( str = "My string")

! Output:-
My string
! Example 2:-
! def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
! printinfo( age = 50, name = "miki" )

! Output:-
Name: miki
Age 50
Default Arguments
! A default argument is an argument that assumes a default value
if a value is not provided in the function call for that argument.
! Example:-
! def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
! printinfo( age = 50, name = "miki" ) Output:-
! printinfo( name = "miki" ) Name: miki
Age 50
Name: miki
Age 35
Variable-Length Arguements
! You may need to process a function for more arguments than
you specified while defining the function.
! These arguments are called variable-length arguments and are
not named in the function definition, unlike required and
default arguments.
! Syntax:-
! def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
! An asterisk (*) is placed before the variable name that
holds the values of all non keyword variable arguments.
! This tuple remains empty if no additional arguments are
specified during the function call.
! Example:-
! def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print ("Output is: ")
print (arg1)
print(“For Loop:”)
for var in vartuple:
print (var)
return Output is:
! printinfo( 10 ) 10
Output is:
! printinfo( 70, 60, “Hello” )
70
For Loop:
60
Hello
! Example:-
! def printinfo( arg1,arg2, *vartuple,**keyword ):
"This prints a variable passed arguments"
print (arg1)
print (arg2)
print (vartuple)
print (keyword)
return
! printinfo( 10 )
! printinfo( 10, 20 )
! printinfo(10, 20, 30, 40, 50, a = 60, b = 70)
! Output:-
! TypeError: printinfo() missing 1 required positional argument:
'arg2’
! Output:-
! 10
! 20
! ()
! {}
! Output:-
! 10
! 20
! (30, 40, 50)
! {‘a’:60, ‘b’:70}
Anonymous Functions
! You can use the lambda keyword to create small anonymous
functions.
! An anonymous function is a function that is defined without a name
! anonymous functions are defined using the lambda keyword.
! Lambda forms can take any number of arguments but return just one
value in the form of an expression. They cannot contain commands or
multiple expressions.
! An anonymous function cannot be a direct call to print because lambda
requires an expression.
! Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the global
namespace.
! Although it appears that lambdas are a one-line version of a function, they
are not equivalent to inline statements in C or C++, whose purpose is to
stack allocation by passing function, during invocation for performance
reasons.
! Syntax:-

lambda [arg1 [,arg2,.....argn]]:expression


! Example:-

#Function definition is here


sum = lambda a,b:a+b

#Now you can call sum as a function


print("Value of total:",sum(10,20))
print("Value of total:",sum(20,20))

Output:-
Value of total: 30
Value of total: 40
map(), filter() and reduce()
! The map(), filter() and reduce() functions bring a bit of functional
programming to Python.

! Allthree of these are convenience functions that can be replaced


with List Comprehensions or loops, but provide a more elegant and
short-hand approach to some problems.
The map() Function
! The map() function iterates through all items in the given iterable
and executes the function we passed as an argument on each
of them.

! Thesyntax is:
! map(function, iterable(s))
The map() Function
def start_with_A(s):
return (s[0] == ‘A')

fruits = ['Apple','Banana','Pear','Apricot']
map_object = map(start_with_A,fruits)
print(list(map_object))
The map() Function
Output:
[True, False, False, True]
!
The map() Function
def calculatesquare(n):
return n*n
num = (1,2,3,4)
result = map(calculatesquare,num)
print(set(result))

Num = (1,2,3,4)
Result = map(lambda n: n*n, Num)
print(set(Result))
The map() Function
! Output:
! {16, 1, 4, 9}
The map() Function and lambda
#map with lambda
fruits = ['Apple','Banana','Pear','Apricot']
map_object = map(lambda s: s[0]=='A',fruits)
print(list(map_object))

#map without lambda


def start_with_A(s):
return (s[0] == ‘A')

fruits = [‘Apple','Banana','Pear','Apricot']
map_object = map(start_with_A,fruits)
print(list(map_object))
The map() Function and lambda
Output:
[True, False, False, True]
The filter() Function
! Similar to map(), filter() takes a function object and an
iterable and creates a new list.
! As the name suggests, filter() forms a new list that contains
only elements that satisfy a certain condition, i.e.
the function we passed returns True.
! The syntax is:
! filter(function, iterable(s))
The filter() Function
def start_with_A(s):
return s[0] == 'A'

fruits = ['Apple','Banana','Pear','Apricot']
filter_object = filter(start_with_A,fruits)
print(list(filter_object))
The filter() Function
! Output:
['Apple', 'Apricot']
The filter() Function
# random list
random_list = [1, 'a', 0, False, True, '0']

filtered_list = filter(None, random_list)

print('The filtered elements are:')


for element in filtered_list:
print(element)
The filter() Function with lambda
fruits = ['Apple','Banana','Pear','Apricot']
filter_object = filter(lambda s: s[0]=='A',fruits)
print(list(filter_object))
The reduce() Function

! reduce() works differently than map() and filter(). It does


not return a new list based on the function and iterable
we've passed. Instead, it returns a single value.

! The syntax is:


! reduce(function, sequence[, initial])

! Also,
in Python 3 reduce() isn't a built-in function anymore,
and it can be found in the functools module.
The reduce() Function
! reduce() works by calling the function we passed for the
first two items in the sequence. The result returned by
the function is used in another call to function alongside
with the next (third in this case), element.
The reduce() Function
The reduce() Function
Python Global, Local and Nonlocal variables
In Python, a variable declared outside of the function or in global scope is known as
a global variable. This means that a global variable can be accessed inside or
outside of the function.

• Example#1

#Global Variable demo


x = “global"

def foo():
print("X inside:",x)

foo()
print("X Outside:”,x)
Python Global, Local and Nonlocal variables
X inside: global
X Outside: global

! Example#2
#Global local variable demo
x = "global"
def foo():
x = x * 2
print("X inside:",x)
foo()
print("X outside:",x)
Python Global, Local and Nonlocal variables
Traceback (most recent call last):
File "Func.py", line 166, in <module>
foo()
File "Func.py", line 164, in foo
x = x * 2
UnboundLocalError: local variable 'x' referenced before assignment
Python Global, Local and Nonlocal variables
#Global local variable demo
x = "global"
def foo():
x = "Local"
x = x * 2
print("X inside:",x)
foo()
print("X outside:”,x)

Output:
X inside: LocalLocal
X outside: global
Python Global, Local and Nonlocal variables

Local Variables
A variable declared inside the function's body or in the local scope is
known as a local variable.

#Only local variable demo


def foo():
x = 2
print("X inside:",x)
foo()
print("X outside:",x)
Python Global, Local and Nonlocal
variables
X inside: 2
Traceback (most recent call last):
File "Func.py", line 174, in <module>
print("X outside:",x)
NameError: name 'x' is not defined
!
Python Global, Local and Nonlocal variables
Using Global and Local variables in the same code

#Global local variable demo


x = "global"
def foo():
global x
y = "Local"
x = x * 3
print(x)
print(y)
foo()
Python Global, Local and Nonlocal variables
Nonlocal Variables
Nonlocal variables are used in nested functions whose local scope
is not defined. This means that the variable can be neither in the
local nor the global scope.

Output:
inner: nonlocal
outer: nonlocal
Recursive Function
! In Python, we know that a function can call other functions.
It is even possible for the function to call itself. These types of
construct are termed as recursive functions.
! The following image shows the working of a recursive
function called recurse.
Recursive Function

! The factorial of 3 is 6
Type Conversion
! Python defines type conversion functions to directly
convert one data type to another.
! int(a,base) : This function converts any data type to
integer. ‘Base’ specifies the base in which string is if data
type is string.
! float() : This function is used to convert any data type to a
floating point number
!s = int(input(),2)
! c = int(s,2)
! print ("After converting to integer base 2 : ", end="")
! print (c)
! e = float(s)
! print ("After converting to float : ", end="")
! print (e)

Output:-
After converting to integer base 2 : 18
After converting to float : 10010.0
! ord() : This function is used to convert a character to
integer.

! hex() : This function is to convert integer to hexadecimal


string.

! oct() : This function is to convert integer to octal string.


!s = '4’
! c = ord(s)
! print ("After converting character to integer : ”)
! print (c)
! c = hex(56)
! print ("After converting 56 to hexadecimal string : “)
! print (c)
! c = oct(56)
! print ("After converting 56 to octal string : “)
! print (c)
Output:-
After converting character to integer : 52
After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70
! tuple() : This function is used to convert to a tuple.

! set() : This function returns the type after converting to set.

! list() : This function is used to convert any data type to a


list type.
!s = 'geeks’
! c = tuple(s)
! print ("After converting string to tuple :”)
! print (c)
! c = set(s)
! print ("After converting string to set : “)
! print (c)
! c = list(s)
! print ("After converting string to list : “)
! print (c)

Output:-
After converting string to tuple : ('g', 'e', 'e', 'k', 's')
After converting string to set : {'k', 'e', 's', 'g'}
After converting string to list : ['g', 'e', 'e', 'k', 's']
! dict(): This function is used to convert a tuple of order
(key,value) into a dictionary.

! str() : Used to convert integer into a string.

! complex(real,imag) : : This function converts real numbers


to complex(real,imag) number.
!a =1
!b=2
! tup = (('a', 1) ,('f', 2), ('g', 3))
! c = complex(1,2)
! print ("After converting integer to complex number : ",end="")
! print (c)
! c = str(a)
! print ("After converting integer to string : ",end="")
! print (c)
! c = dict(tup)
! print ("After converting tuple to dictionary : ",end="")
Output:-
! print (c)
After converting integer to complex number : (1+2j)
After converting integer to string : 1
After converting tuple to dictionary : {'a': 1, 'f': 2, 'g': 3}
Math Module
! The math module is a standard module in Python and is
always available.
! To use mathematical functions under this module, you
have to import the module using import math.
! This module does not support complex datatypes. The
cmath module with a brief explanation of what they do.
List of functions in Python Math Module
! ceil(x) :- Returns the smallest integer greater than or equal to x.
! copysign(x, y) :- Returns x with the sign of y
! fabs(x) :- Returns the absolute value of x
! factorial(x) :- Returns the factorial of x
! floor(x) :- Returns the largest integer less than or equal to x
! fmod(x, y) :- Returns the remainder when x is divided by y
! frexp(x) : - Returns the mantissa and exponent of x as the pair (m, e)
! fsum(iterable) :- Returns an accurate floating point sum of values in
the iterable
! isfinite(x) :- Returns True if x is neither an infinity nor a NaN (Not a
Number)
! isinf(x) :- Returns True if x is a positive or negative infinity
! isnan(x) :- Returns True if x is a NaN(Not a Number)
! ldexp(x, i) :- Returns x * (2**i)
! modf(x) :- Returns the fractional and integer parts of x
! trunc(x) :- Returns the truncated integer value of x
! exp(x) :- Returns e**x
! expm1(x) :- Returns e**x - 1
! log(x[, base]) :- Returns the logarithm of x to the base (defaults to e)
! log1p(x) :- Returns the natural logarithm of 1+x
! log2(x) :- Returns the base-2 logarithm of x
! log10(x) :- Returns the base-10 logarithm of x
! pow(x, y) :- Returns x raised to the power y
! sqrt(x) :- Returns the square root of x
! acos(x) :- Returns the arc cosine of x
! asin(x) :- Returns the arc sine of x
! atan(x) :- Returns the arc tangent of x
Strings
Introduction
!A string is a sequence of characters. You can access the
characters one at a time with the bracket operator:
>>> fruit = "Banana"
>>> letter = fruit[1]
>>> print(letter)
a
>>> letter = fruit[1.5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
Accessing Values in Strings
>>> var1 = "Hello World!!"
>>> var2 = "Python Programming"
>>> print("var1[0]", var1[0])
var1[0] H
>>> print("var2[0]", var2[0])
var2[0] P
>>> print("var1[1:6]", var1[1:6])
var1[1:6] ello
>>> print("var1[0:6]", var1[0:7])
var1[0:6] Hello W
>>> print("var1[:]", var1[:])
var1[:] Hello World!!
>>> print("var1[1:]", var1[1:])
var1[1:] ello World!!
>>> print("var1[:13]", var1[:13])
var1[:13] Hello World!!
>>> print("var1[:8]", var1[:8])
var1[:8] Hello Wo
Accessing Values in Strings
>>> my_string = 'Hello'
>>> print(my_string)
Hello
>>> my_string = "Hello"
>>> print(my_string)
Hello
>>> my_string = "'Hello'"
>>> print(my_string)
'Hello'
>>> my_string = '"Hello"'
>>> print(my_string)
"Hello"
>>> my_string = """Hell, welcome to
... the world of python"""
>>> print(my_string)
Hell, welcome to
the world of python
Updating the string
>>> print("Updated String: ",var[:6]+'Python')
>>> print("Updated String: ",var1[:6]+'Python')
Updated String: Hello Python
How to change or delete a string?
! Strings are immutable. This means that elements of a string cannot be
changed once it has been assigned. We can simply reassign different
strings to the same name.
>>> my_string = 'programming'
>>> my_string[5] = 'x'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> my_string
'programming'
>>> del my_string[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object doesn't support item deletion
>>> del my_string
>>> my_string
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'my_string' is not defined
Iterating Through String
! Ex: to count no. of ‘l’ in a string
Iterating Through String
! Ex: to count no. of ‘l’ in a string

count = 0
for letter in 'Hello World':
if(letter == ‘l'):
count += 1
print('%d letters found' %count)
Escape Sequence
He said, “What’s up?”
! Ifwe want to print a text like - He said, "What's there?"- we
can neither use single quote or double quotes. This will
result into SyntaxError as the text itself contains both single
and double quotes.
>>> print("He said, "What's up?"")
File "<stdin>", line 1
print("He said, "What's up?"")
^
SyntaxError: invalid syntax
>>> print("He said, "What's up?'")
File "<stdin>", line 1
print("He said, "What's up?'")
^
SyntaxError: invalid syntax
Escape Sequence
>>> print('''He said, "What's there?"''')
He said, "What's there?"
>>> print('He said,"What\'s there?"')
He said,"What's there?"
>>> print("He said,\"What's there?\"")
He said,"What's there?"
Escape characters
Escape characters
>>> print("C:\\Python32\\Lib")
C:\Python32\Lib
>>> print("This is printed\nin two lines")
This is printed
in two lines
>>> print("This is \x48\x45\x58 representation")
This is HEX representation
String special operators
! Assume string variable a holds 'Hello' and variable b holds
'Python', then −
print("This is \x61 \ngood example!!")
print(r"This is \x61 \ngood example!!”)

! Output:
This is a
good example!!
This is \x61 \ngood example!!
! Ifwe want to concatenate strings in different lines, we can
use parentheses.
>>> s = ('Hello'
... 'World!')
>>> print(s)
HelloWorld!
The format() Method for Formatting Strings
! The format() method that is available with the string object is
very versatile and powerful in formatting strings.
! Format strings contains curly braces {} as placeholders.
! We can use positional arguments or keyword arguments to
specify the order.
The format() Method for Formatting Strings
#default (implicit) order
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('\n---Default Order---')
print(default_order)

#Order using positional arguments


positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')
print('\n--- Positional Order ---')
print(positional_order)

# order using keyword argument


keyword_order = "{s}, {b} and
{j}".format(j='John',b='Bill',s='Sean')
print('\n--- Keyword Order ---')
print(keyword_order)
The format() Method for Formatting Strings
---Default Order---
John, Bill and Sean

--- Positional Order ---


Bill, John and Sean

--- Keyword Order ---


Sean, Bill and John
The format() Method for Formatting Strings
Format Codes Description
d For integers
f For floating point numbers
b For binary numbers
o For octal numbers
x For octal hexadecimal numbers
s For strings
e For floating point in exponential format
The format() Method for Formatting Strings
#positional arguments
print("Hello {0}, your balance is {1:f}".format("Adam",230.2346))
print("Hello {0}, your balance is {1:10f}".format("Adam",230.2346))
print("Hello {0}, your balance is
{1:10.4f}”.format("Adam",230.2346))
print("Hello {0}, your balance is {1}".format("Adam",230.2346))

#keyword arguments
print("Hello {name}, your balance is
{blc:9.4f}".format(name="Adam",blc=230.2346))
The format() Method for Formatting Strings
! Output
Hello Adam, your balance is 230.234600
Hello Adam, your balance is 230.234600
Hello Adam, your balance is 230.2346
Hello Adam, your balance is 230.2346
Hello Adam, your balance is 230.2346
The format() Method for Formatting Strings
# default arguments
print("Hello {}, your balance is {}.".format("Adam", 230.2346))
# positional arguments
print("Hello {0}, your balance is {1}.".format("Adam", 230.2346))
# keyword arguments
print("Hello {name}, your balance is {blc}.".format(name="Adam",
blc=230.2346))
# mixed arguments
print("Hello {0}, your balance is {blc:5.6f}.".format("Adam",
blc=230.2346))
The format() Method for Formatting Strings
! Output
Hello Adam, your balance is 230.2346.
Hello Adam, your balance is 230.2346.
Hello Adam, your balance is 230.2346.
Hello Adam, your balance is 230.234600.
Numbers formatting with format()
# integer arguments
print("The number is:{:d}".format(123))
# float arguments
print("The float number is:{:f}".format(123.4567898))
# octal, binary and hexadecimal format
print("bin: {0:b}, oct: {0:o}, hex: {0:x}”.format(12))

Output:
The number is:123
The float number is:123.456790
bin: 1100, oct: 14, hex: c
Numbers formatting with format()
# integer numbers with minimum width
print("{:5d}".format(12))
# width doesn't work for numbers longer than padding
print("{:2d}".format(1234))
# padding for float numbers
print("{:8.3f}".format(12.2346))
# integer numbers with minimum width filled with zeros
print("{:05d}".format(12))
# padding for float numbers filled with zeros
print(“{:08.3f}".format(12.2346))
Output:
12
1234
12.235
00012
0012.235
Numbers formatting with alignment

Type Meaning

< Left aligned to the remaining space

^ Centre aligned to the remaining space

> Right aligned to the remaining space

= Forces the signed (+)(-) to the leftmost position


print("{:5d}".format(12))
print("{:^10.3f}".format(12.2346))
print("{:<05d}".format(12))
print(“{:=8.3f}".format(-12.2346))

Output:
12
12.235
12000
- 12.235
# string padding with left alignment
print("{:<5}".format("cat"))
# string padding with right alignment
print("{:>5}".format("cat"))
# string padding with center alignment
print("{:^5}".format("cat"))
# string padding with center alignment
# and '*' padding character
print(“{:*^5}".format("cat"))
Output:
cat
cat
cat
*cat*
Truncating strings with format()
# truncating strings to 3 letters
print("{:.3}".format("caterpillar"))
# truncating strings to 3 letters
# and padding
print("{:<5.3}".format("caterpillar"))
# truncating strings to 3 letters,
# padding and center alignment
print(“{:^5.3}".format("caterpillar"))

Output:
cat
cat
cat
String Formatting Operator
! One of Python's coolest features is the string format operator
%. This operator is unique to strings and makes up for the
pack of having functions from C's printf() family. Following is
a simple example −

! Ex:
print("My name is %s and weight is %d kg!" % ('Zara', 21))
! Output:
My name is Zara and weight is 21 kg!
! Ex:
print("My name is %s and weight is %d kg!" % ('Zara', 21))
print("The character is %c” %'Z')
print("My value is %i " %1.0)
print("My value is %e " %10)
print("My value is %f" %10)
! Output:
My name is Zara and weight is 21 kg!
The character is Z
My value is 1
My value is 1.000000e+01
My value is 10.000000
Methods of String Objects
! capitalize(): Capitalises first letter of string
! Ex:
str = "hello world"
print("str.capitalize() : ", str.capitalize())
! Output:
('str.capitalize() : ', 'Hello world’)
! center(width, fillchar): Returns a space-padded string with
the original string centered to a total of width columns.
Padding is done using the specified fillchar. Default filler is a
space.
Methods of String Objects
str = "hello!"
print("str.center() : ",str.center(10,'a'))
print("str.center() : ",str.center(10))
str="Hello"
print("str.center() : “,str.center(10,'a'))

Output:
('str.center() : ', 'aahello!aa')
('str.center() : ', ' hello! ')
('str.center() : ', 'aaHelloaaa')
Methods of String Objects
! count(str, beg= 0,end=len(string)): Counts how many times
str occurs in string or in a substring of string if starting index
beg and ending index end are given.

str = "This is string example....hello!!!"


sub = "i"
print("str.count() : ",str.count(sub))
print("str.count() : ",str.count("i"))
print("str.count() : ",str.count(sub,4))
print("str.count() : “,str.count(sub,4,len(str)))
print("str.count() : ",str.count(sub,4,11))
print("str.count() : ",str.count(sub,4,12))
Methods of String Objects
('str.count() : ', 3)
('str.count() : ', 3)
('str.count() : ', 2)
('str.count() : ', 2)
('str.count() : ', 1)
('str.count() : ', 2)
!
Methods of String Objects
! encode(encoding=‘UTF-8’,errors=‘strict'): The
method encode() returns an encoded version of the string.
Default encoding is the current default string encoding. The
errors may be given to set a different error handling scheme.
! decode(encoding=‘UTF-8’,errors='strict'): The
method decode() decodes the string using the codec
registered for encoding. It defaults to the default string
encoding.
str = 'pythön!'
str_en = str.encode('ascii','ignore')
str_de = str_en.decode('ascii','ignore')
print("Encoded String:",str_en)
print("Encoded String:",str_de)
'''
print("Encoded String:",str.encode('utf-8','strict'))
#print("Encoded String:",str.encode('ascii','strict'))
print("Encoded String:",str.encode('ascii','ignore'))
print("Encoded String:",str.encode('ascii','replace'))
print("Encoded String:",str.decode('ascii','replace'))
'''
Methods of String Objects
! endswith(suffix, beg=0, end=len(string)): Determines if string or a
substring of string (if starting index beg and ending index end are
given) ends with suffix; returns true if so and false otherwise

str = "Hello World!!"


suffix = "World!!"
str_suf = str.endswith(suffix)
str_suf = str.endswith(suffix,3)
str_suf = str.endswith(suffix,10)
suffix = "llo"
str_suf = str.endswith(suffix,2,5)
str_suf = str.endswith(suffix,2,4)
str_suf = str.endswith(suffix,2)
print("Ans: ",str_suf)
Methods of String Objects
! expandtabs(tabsize=8): Expands tabs in string to multiple
spaces; defaults to 8 spaces per tab if tabsize not provided.

str = "Hello\tworld!!"
print("Original String: ",str)
print("Original String: ",str.expandtabs())
print("Original String: ",str.expandtabs(8))
print("Original String: “,str.expandtabs(16))
Methods of String Objects
! expandtabs(tabsize=8): Expands tabs in string to multiple
spaces; defaults to 8 spaces per tab if tabsize not provided.

! Output:
Original String: Hello world!!
Original String: Hello world!!
Original String: Hello world!!
Original String: Hello world!!
Methods of String Objects
! find(str,beg=0 end=len(string)): Determine if str occurs in
string or in a substring of string if starting index beg and
ending index end are given returns index if found and -1
otherwise.

str1 = "This is string example....hello!!!"


str2 = "exam"
print(str1.find(str2))
print(str1.find(str2,10))
print(str1.find(str2,17))
print(str1.find(str2,10,len(str1)))
print(str1.find(str2,17,len(str1)))
Methods of String Objects
! find(str,beg=0 end=len(string)): Determine if str occurs in
string or in a substring of string if starting index beg and
ending index end are given returns index if found and -1
otherwise.
! Output:
15
15
-1
15
-1
Methods of String Objects
! index(str,
beg=0, end=len(string)): Same as find(), but raises
an exception if str not found.

str1 = "This is string example....hello!!!"


str2 = "exam"
print(str1.index(str2))
print(str1.index(str2,10))
print(str1.index(str2,17))
print(str1.index(str2,10,len(str1)))
print(str1.index(str2,17,len(str1)))
Methods of String Objects
! rfind(str,beg=0,end=len(string)): The method rfind() returns the
last index where the substring str is found, or -1 if no such index
exists, optionally restricting the search to string[beg:end].

str1 = "This is string example....hello!!!This is really a string!"


str2 = "is"
print(str1.rfind(str2))
print(str1.rfind(str2,0,10))
print(str1.rfind(str2,10,0))
print(str1.find(str2))
print(str1.find(str2,0,10))
print(str1.find(str2,10,0))
Methods of String Objects
! rfind(str,beg=0,end=len(string)): The method rfind() returns
the last index where the substring str is found, or -1 if no such
index exists, optionally restricting the search to
string[beg:end].
! Output:
39
5
-1
2
2
-1
Methods of String Objects
! rindex( str, beg=0, end=len(string)): The
method rindex() returns the last index where the
substring str is found, or raises an exception if no such index
exists, optionally restricting the search to string[beg:end].

print("rindex: ",str1.rindex(str2))
print("index: ",str1.index(str2))
print("rindex: ",str1.rindex(str2,0,10))
print("index: ",str1.index(str2,10,len(str1)))
Methods of String Objects
! Output:
rindex: 15
index: 15
Traceback (most recent call last):
File "Strings.py", line 217, in <module>
print("rindex: ",str1.rindex(str2,0,10))
ValueError: substring not found
!
Methods of String Objects
! isalnum():Returns true if string has at least 1 character and
all characters are alphanumeric and false otherwise.

str = "Thisis2021"
print(str.isalnum())
str1 = "This is string example....hello!!!"
print(str1.isalnum())

Output:
True
False
Methods of String Objects
! isalpha(): returns True if all the characters are alphabet
letters (a-z).
! Example of characters that are not alphabet letters:
(space)!#%&? etc.

str = "Thisis2021"
print(str.isalpha())
str1 = "This is string example....hello!!!"
print(str1.isalpha())
str2 = "hello"
print(str2.isalpha())
Methods of String Objects
! isdigit():
Returns true if string contains only digits and false
otherwise.

str3 = "hello"
print(str3.isdigit())
str4 = "1234"
print(str4.isdigit())
Methods of String Objects
! islower(): This method returns true if all cased characters in the
string are lowercase and there is at least one cased
character, false otherwise.
! isspace(): Returns true if string contains only whitespace
characters and false otherwise.
! istitle(): The method istitle() checks whether all the case-based
characters in the string following non-casebased letters are
uppercase and all other case-based characters are
lowercase
! isupper(): The method isupper() checks whether all the case-
based characters (letters) of the string are uppercase.
Methods of String Objects
str1 = "This is string example....hello!!!"
print("Lower: ",str1.islower())
str1 = "this is string example....hello!!!"
print("Lower: ",str1.islower())
print("Space: ",str1.isspace())
str1 = " "
print("Space: ",str1.isspace())
str1 = "this is string example....hello!!!"
print("Title: ",str1.istitle())
str1 = "This Is String Example....Hello!!!"
print("Title: ",str1.istitle())
str1 = "This Is String Example....Hello!!!"
print("Upper: ",str1.isupper())
str1 = "THIS IS STRING EXAMPLE...HELLO!!!"
print("Upper: ",str1.isupper())
Methods of String Objects
! Output:
Lower: False
Lower: True
Space: False
Space: True
Title: False
Title: True
Upper: False
Upper: True
Methods of String Objects
! join(seq):The method join() returns a string in which the
string elements of sequence have been joined
by str separator.

! len(string): Returns the length of the string


Methods of String Objects
s = "-"
seq = ("a","b","c")
print("Joint : ",s.join(seq))
str = "This is string example....hello!!!"
print("Lenth :",len(str))

Output:
Joint : a-b-c
Lenth : 34
Methods of String Objects
! lstrip():The method lstrip() returns a copy of the string in
which all chars have been stripped from the beginning of
the string (default whitespace characters).
! rstrip()
The method rstrip() returns a copy of the string in which
all chars have been stripped from the end of the string
(default whitespace characters).
Methods of String Objects
str = "88888888888This is string example....hello!!!88888888888"
print("Left Strip: ",str.lstrip('8'))
print("Right Strip: “,str.rstrip(‘8'))
print("Strip: ",str.strip('8'))

Output:
Left Strip: This is string example....hello!!!88888888888
Right Strip: 88888888888This is string example….hello!!!
Strip: This is string example....hello!!!
Methods of String Objects
! max(str): The method max() returns the max alphabetical
character from the string str.
! min(str): The method min() returns the min alphabetical
character from the string str.
str = "This is string example....hello!!!"
print("Strip: ",str.lstrip())
print("Max String: ",max(str))
print("Min String: “,min(str))

Output:
Max String: x
Min String:
Methods of String Objects
! replace(old, new [, max]): The method replace() returns a copy
of the string in which the occurrences of old have been replaced
with new, optionally restricting . the number of replacements
to max.
str = "This is string example....hello!!!This is really a string"
print("After replacement: ",str.replace("is","was"))
print("After replacement: “,str.replace("is","was",3))

Output:
After replacement: Thwas was string example....hello!!!Thwas was really
a string
After replacement: Thwas was string example....hello!!!Thwas is really a
string
Methods of String Objects
! ljust(width[, fillchar]): The method ljust() returns the string left
justified in a string of length width. Padding is done using the
specified fillchar (default is a space). The original string is
returned if width is less than len(s).
! rjust(width,[, fillchar]): The method rjust() returns the string
right justified in a string of lengthwidth. Padding is done using
the specified fillchar (default is a space). The original string is
returned if width is less than len(s).
Methods of String Objects
str1 = "This is string example....hello!!!"
print("Right justified: ",str1.rjust(50,'0'))
print("left justified: “,str1.ljust(50,'0'))

Output:
Right justified: 0000000000000000This is string example....hello!!!
left justified: This is string example….hello!!!0000000000000000
Methods of String Objects
! startswith(str,
beg=0,end=len(string)): Determines if string or a
substring of string (if starting index beg and ending index
end are given) starts with substring str; returns true if so and
false otherwise.
str = "This is string example....hello!!!"
prefix = "This"
str_pre = str.startswith(prefix)
print(str_pre)
str_pre = str.startswith(prefix,0)
print(str_pre)
str_pre = str.startswith("is",4,9)
print(str_pre)
Methods of String Objects
! startswith(str,
beg=0,end=len(string)): Determines if string or a
substring of string (if starting index beg and ending index
end are given) starts with substring str; returns true if so and
false otherwise.
True
True
False
Methods of String Objects
! swapcase(): Inverts case for all letters in string.

str = "This is string example....Hello!!!"


print(str.swapcase())
str = "THIS IS STRING EXAMPLE....HELLO!!!"
print(str.swapcase())

Output:
tHIS IS STRING EXAMPLE....hELLO!!!
this is string example....hello!!!
Methods of String Objects
! title():The method title() returns a copy of the string in which
first characters of all the words are capitalised.

! lower(): Converts all uppercase letters in string to lowercase.

! upper(): Converts lowercase letters in string to uppercase.


Methods of String Objects
str = "This is string example....Hello!!!"
print(str.title())
str1 = "THIS IS STRING EXAMPLE....HELLO!!!"
print(str1.lower())
str = "This is string example....Hello!!!"
print(str.upper())

Output:
This Is String Example....Hello!!!
this is string example....hello!!!
THIS IS STRING EXAMPLE....HELLO!!!
Methods of String Objects
! zfill(width): The method zfill() pads string on the left with
zeros to fill width.
! split(): The method split() returns a list of all the words in the
string, using str as the separator (splits on all whitespace if
left unspecified), optionally limiting the number of splits
to num.
Methods of String Objects
str = "This is string example....Hello!!!"
print(str.zfill(40))
print(str.split())
print(str.split(' ‘,2))

Output:
000000This is string example....Hello!!!
['This', 'is', 'string', 'example....Hello!!!']
['This', 'is', 'string example....Hello!!!']
Methods of String Objects
! Python does not handle uppercase and lowercase letters the
same way that people do. All the uppercase letters come
before all the lowercase letters.

word = ‘Pineapple'
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")
Methods of String Objects
! Python does not handle uppercase and lowercase letters
the same way that people do. All the uppercase letters
come before all the lowercase letters.

! Output:
Your word,Pineapple,comes before banana
Functional
Approach in
Python
! Functional programming is all about
expressions. We may say that the
Functional programming is an expression
oriented programming.
! Expression oriented functions of Python
provides are:
lambda
map(aFunction, aSequence)
filter(aFunction, aSequence)
reduce(aFunction, aSequence)
list comprehension
lambda function
!A way to create small anonymous
functions, i.e. functions without a name.
! Mainly used in combination with the
functions filter(), map() and reduce().
! Syntax:

lambda argument_list: expression


! Ex:
def add(x,y):
return x+y

# call the function


print(add(2,3)) # output : 5

#Functional approach
add = lambda x, y : x + y
print(add(2,3))

Output:
5
! Ex:
f = lambda x: x<100
print(f(90))

Output:
True

! Ex:
f = lambda x: 'big' if x > 100 else 'small'
print(f(100))

Output:
small
Map() function
! Themap(aFunction, aSequence) function
applies a passed-in function to each item
in an iterable object and returns a list
containing all the function call results.
! Ex:

items = [1, 2, 3, 4, 5]
def sqr(x):
return x ** 2
print(list(map(sqr, items)))

Output:
[1, 4, 9, 16, 25]
! Ex:

#python 3
items = [1, 2, 3, 4, 5]
print(list(map((lambda x: x **2), items)))

#python 2
items = [1, 2, 3, 4, 5]
print(map((lambda x: x **2), items))
! While we still use lamda as a aFunction, we can
have a list of functions as aSequence.
! Ex:
def square(x):
return (x**2)
def cube(x):
return (x**3)
funcs = [square, cube]
for r in range(5):
value = list(map(lambda x: x(r), funcs))
print(value)
! Output:

[0, 0]
[1, 1]
[4, 8]
[9, 27]
[16, 64]
! Multiple iterables to the map function
! Ex:

a = [1, 2, 3]
b = [10, 20, 30]
print(list(map(lambda x, y: x + y, a, b)))

Output:
[11,22,33]
filter() function
! Thefilter(aFunction, aSequence) function
applies a passed-in function to each item
in an iterable object and extracts each
element in the sequence for which the
function returns True.
! Ex:-
list(range(-5,5))
# [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
print(list(filter((lambda x: x < 0), range(-5,5))))
print(list(map((lambda x: x < 0), range(-5,5))))

Output:-
[-5, -4, -3, -2, -1]
[True, True, True, True, True, False, False, False,
False, False]
Finding intersections of two lists
! Ex:
a = [1,2,3,5,7,9]
b = [2,3,5,6,7,8]

print(filter((lambda x: x in a), b))

Output:-
[2, 3, 5, 7]
! Ex:

fib = [0,1,1,2,3,5,8,13,21,34,55]
result = filter(lambda x: x % 2, fib)
print(result)
result = filter(lambda x: x % 2 == 0, fib)
print(result)

Output:
[1, 1, 3, 5, 13, 21, 55]
[0, 2, 8, 34]
How filter() method works
without the filter function?
! Ex:

# random list
randomList = [1, 'a', 0, False, True, '0']
filteredList = filter(None, randomList)
print('The filtered elements are:')
for element in filteredList:
print(element)
! Output:

The filtered elements are:


1
a
True
0
reduce() function
! reduce(aFunction, aSequence)
! It applies a rolling computation to sequential pairs
of values in a list.
! Ex:

from functools import reduce #python3


print(reduce( (lambda x, y: x * y), [1, 2, 3, 4] ))

Output:
24
! Ex:

from functools import reduce


#python3
print(reduce( (lambda x, y: x / y), [1, 2,
3, 4] ))

Output:
0.041666666666666664
! Determining the maximum of a list of
numerical values by using reduce:

from functools import reduce


f = lambda a,b: a if (a > b) else b
print(reduce(f, [47,11,42,102,13]))

Output:
102
! Calculating the sum of the numbers from 1
to 100:

from functools import reduce


print(reduce(lambda x, y: x+y,
range(1,101)))

Output:
5050

You might also like