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

Python_Module2_Notes

Module II of Python Programming on Raspberry PI covers the creation and use of functions, including built-in and user-defined functions, as well as string manipulation techniques. It discusses various built-in functions like max(), min(), len(), type conversion functions, and random number generation using the random module. Additionally, it introduces mathematical functions from the math module and emphasizes the importance of parameters and arguments in functions.
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)
3 views

Python_Module2_Notes

Module II of Python Programming on Raspberry PI covers the creation and use of functions, including built-in and user-defined functions, as well as string manipulation techniques. It discusses various built-in functions like max(), min(), len(), type conversion functions, and random number generation using the random module. Additionally, it introduces mathematical functions from the math module and emphasizes the importance of parameters and arguments in functions.
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/ 22

Python Programming on Raspberry PI (22ECE136) Module II

MODULE II

FUNCTIONS

Creation of functions
Passing parameters and return values

STRINGS

String Manipulation
String methods

Dept of ECE, BNMIT Page 1


Python Programming on Raspberry PI -22ECE136 Module II

FUNCTIONS

 Functions are the building blocks of any programming language.


 A sequence of instructions intended to perform a specific independent task is known as a function.
 In this section, we will discuss various types of built-in functions, user-defined functions, applications/uses
of functions etc.
 Built-in Functions
 Python provides a rich set of built-in functions for doing various tasks.
 The programmer/user need not know the internal working of these functions; instead, they need to
know only the purpose of such functions.
 Some of the built in functions are given below –
 max(): This function is used to find maximum value among the arguments. It can be used for
numeric values or even to strings.
 max(10, 20, 14, 12) #maximum of 4 integers
20
 max("hello world")
'w' #character having maximum ASCII code
 max(3.5, -2.1, 4.8, 15.3, 0.2)
15.3 #maximum of 5 floating point values

 min(): As the name suggests, it is used to find minimum of arguments.


 min(10, 20, 14, 12) #minimum of 4 integers
10
 min("hello world")
'' #space has least ASCII code here
 min(3.5, -2.1, 4.8, 15.3, 0.2)
-2.1 #minimum of 5 floating point values

 len(): This function takes a single argument and finds its length. The argument can be a string, list,
tuple etc.
 len(“hello how are you?”)
18
There are many other built-in functions available in Python. They are discussed in further Modules,
wherever they are relevant.
 Type Conversion Functions
 As we have seen earlier (while discussing input() function), the type of the variable/value can be
converted using functions int(), float(), str().
 Python provides built-in functions that convert values from one type to another
 Consider following few examples –

Dept of ECE, BNMIT Page 2


Python Programming on Raspberry PI -22ECE136 Module II

 int('20') #integer enclosed within single quotes


20 #converted to integer type
 int("20") #integer enclosed within double quotes
20
 int("hello") #actual string cannot be converted to int

Traceback (most recent call last):


File "<pyshell#23>", line 1, in <module> int("hello")
ValueError: invalid literal for int() with base 10: 'hello'
 int(3.8) #float value being converted to integer
3 #round-off will not happen, fraction is ignored
 int(-5.6)
-5
 float('3.5') #float enclosed within single quotes
3.5 #converted to float type
 float(42) #integer is converted to float
42.0
 str(4.5) #float converted to string
'4.5'
 str(21) #integer converted to string
'21'
 Random Numbers
 Most of the programs that we write are deterministic.
 That is, the input (or range of inputs) to the program is pre-defined and the output of the program is
one of the expected values.
 But, for some of the real-time applications in science and technology, we need randomly generated
output. This will help in simulating certain scenario.
 Random number generation has important applications in games, noise detection in electronic
communication, statistical sampling theory, cryptography, political and business prediction etc. These
applications require the program to be nondeterministic.
 There are several algorithms to generate random numbers. But, as making a program completely
nondeterministic is difficult and may lead to several other consequences, we generate pseudo-
random numbers.
 That is, the type (integer, float etc) and range (between 0 and 1, between 1 and 100 etc) of the random
numbers are decided by the programmer, but the actual numbers are unknown.
 Moreover, the algorithm to generate the random number is also known to the programmer. Thus, the
random numbers are generated using deterministic computation and hence, they are known as pseudo-
random numbers!!
 Python has a module random for the generation of random numbers. One has to import this module
in the program. The function used is also random().

Dept of ECE, BNMIT Page 3


Python Programming on Raspberry PI -22ECE136 Module II

 By default, this function generates a random number between 0.0 and 1.0 (excluding 1.0).
 For example –

import random #module random is imported
print(random.random()) #random() function is invoked
0.7430852580883088 #a random number generated

print(random.random())
0.5287778188896328 #one more random number


Importing a module creates an object.

Using this object, one can access various functions and/or variables defined in that module.
Functions are invoked using a dot operator.
 There are several other functions in the module random apart from the function random(). (Do not
get confused with module name and function name. Observe the parentheses while referring a
function name).
 Few are discussed hereunder:
 randint(): It takes two arguments low and high and returns a random integer between these two
arguments (both low and high are inclusive). For example,
>>>random.randint(2,20)
14 #integer between 2 and 20 generated
>>> random.randint(2,20)
10
Various other functions available in random module can be used to generate random numbers following
several probability distributions like Gaussian, Triangular, Uniform, Exponential, Weibull, Normal etc

 Math Functions
 Python provides a rich set of mathematical functions through the module math.
 To use these functions, the math module has to be imported in the code.
 Some of the important functions available in math are given hereunder
 sqrt(): This function takes one numeric argument and finds the square root of that argument.
>>> math.sqrt(34) #integer argument
5.830951894845301
>>> math.sqrt(21.5) #floating point argument
4.636809247747852

 pi: The constant value pi can be used directly whenever we require.


>>>print (math.pi)
3.141592653589793

 log10(): This function is used to find logarithm of the given argument, to the base 10.

Dept of ECE, BNMIT Page 4


Python Programming on Raspberry PI -22ECE136 Module II

>>> math.log10(2)
0.3010299956639812
 log(): This is used to compute natural logarithm (base e) of a given number.
>>> math.log(2)
0.6931471805599453

 sin(): As the name suggests, it is used to find sine value of a given argument. Note that, the argument
must be in radians (not degrees). One can convert the number of degrees into radians by multiplying
pi/180 as shown below –
>>>math.sin(90*math.pi/180) #sin(90) is 1
1.0

 cos(): Used to find cosine value –


>>>math.cos(45*math.pi/180)
0.7071067811865476

 tan(): Function to find tangent of an angle, given as argument.


>>> math.tan(45*math.pi/180)
0.9999999999999999

 pow(): This function takes two arguments x and y, then finds x to the power of y.
>>> math.pow(3,4)
81.0
 User-defined Functions
 Python facilitates programmer to define his/her own functions.
 The function written once can be used wherever and whenever required.
 The syntax of user-defined function would be –
def fname(arg_list):
statement_1
statement_2
……………
Statement_n
return value

 Here def is a keyword indicating it as a function definition.


fname is any valid name given to the function
arg_list is list of arguments taken by a function. These are treated as inputs to the function
from the position of function call. There may be zero or more arguments to a
function.
statements are the list of instructions to perform required task.

Dept of ECE, BNMIT Page 5


Python Programming on Raspberry PI -22ECE136 Module II

return is a keyword used to return the output value. This statement is optional

 The first line in the function def fname(arg_list)is known as function header/definition. The
remaining lines constitute function body.
 The function header is terminated by a colon and the function body must be indented.
 To come out of the function, indentation must be terminated.
 Unlike few other programming languages like C, C++ etc, there is no main()
function or specific location where a user-defined function has to be called.
 The programmer has to invoke (call) the function wherever required.
 Consider a simple example of user-defined function –

def myfun():
 Observe indentation
print("Hello") print("Inside
- Statements outside the function without
the function")
indentation.

print("Example of function")
myfun() myfun()is called here.
print("Example over")

 The output of above program would be –


Example of function
Hello
Inside the function
Example over
 The function definition creates an object of type function.
 In the above example, myfun is internally an object.
 This can be verified by using the statement –
>>>print(myfun) # myfun without parenthesis
<function myfun at 0x0219BFA8>
>>> type(myfun) # myfun without parenthesis
<class 'function'>

 Here, the first output indicates that myfun is an object which is being stored at the memory address
0x0219BFA8 (0x indicates octal number).
 The second output clearly shows myfun is of type function.

(NOTE: In fact, in Python every type is in the form of class. Hence, when we apply type on any
variable/object, it displays respective class name. The detailed study of classes will be done in Module
4.)
 The flow of execution of every program is sequential from top to bottom, a function can be invoked
only after defining it.
Dept of ECE, BNMIT Page 6
Python Programming on Raspberry PI -22ECE136 Module II

 Usage of function name before its definition will generate error. Observe the following code:

print("Example of function")
myfun() #function call before definition
print("Example over")

def myfun(): #function definition is here


print("Hello")
print("Inside the function")

 The above code would generate error saying


NameError: name 'myfun' is not defined
 Functions are meant for code-reusability. That is, a set of instructions written as a function need not
be repeated. Instead, they can be called multiple times whenever required.
 Consider the enhanced version of previous program as below –


The output is –
Example of function Inside
myfun() Inside repeat()
Inside myfun() Example
over

 Observe the output of the program to understand the flow of execution of the program.
 Initially, we have two function definitions myfun()and repeat()one after the other. But, functions are
not executed unless they are called (or invoked). Hence, the first line to execute in the above program
is –
print("Example of function")

 Then, there is a function call repeat(). So, the program control jumps to this function. Inside
repeat(), there is a call for myfun().
 Now, program control jumps to myfun()and executes the statements inside and returns back to

Dept of ECE, BNMIT Page 7


Python Programming on Raspberry PI -22ECE136 Module II

repeat() function. The statement print(“Inside repeat()”) is executed.


 Once again there is a call for myfun()function and hence, program control jumps there. The
function myfun() is executed and returns to repeat().
 As there are no more statements in repeat(), the control returns to the original position of its call.
Now there is a statement print("Example over")to execute, and program is terminated.

 Parameters and Arguments
 In the previous section, we have seen simple example of a user-defined function, where the
function was without any argument.
 But, a function may take arguments as an input from the calling function.
 Consider an example of a function which takes a single argument as below –

def test(var):
print("Inside test()")
print("Argument is ",var)

print("Example of function with arguments")


x="hello"
test(x)
y=20
test(y)
print("Over!!")

 The output would be –


Example of function with arguments
Inside test()
Argument is hello
Inside test()
Argument is 20
Over!!
 In the above program, var is called as parameter and x and y are called as arguments.
 The argument is being passed when a function test() is invoked. The parameter receives the
argument as an input and statements inside the function are executed.
 As Python variables are not of specific data types in general, one can pass any type of value to the
function as an argument.
 Python has a special feature of applying multiplication operation on arguments while passing them
to a function. 
 Consider the modified version of above program –

Dept of ECE, BNMIT Page 8


Python Programming on Raspberry PI -22ECE136 Module II

def test(var):
print("Inside test()")
print("Argument is ",var)

print("Example of function with arguments")


x="hello"
test(x*3)
y=20
test(y*3)
print("Over!!")

 The output would be –


Example of function with arguments
Inside test()
Argument is hellohellohello #observe repetition Inside
test()
Argument is 60 #observe multiplication
Over!!

 One can observe that, when the argument is of type string, then multiplication indicates that string is
repeated 3 times.
 Whereas, when the argument is of numeric type (here, integer), then the value of that argument is
literally multiplied by 3.
 A function that performs some task, but do not return any value to the calling function is known as
void function. The examples of user-defined functions considered till now are void functions.
 The function which returns some result to the calling function after performing a task is known as
fruitful function.
 One can write a user-defined function so as to return a value to the calling function as shown in
the following example –
def sum(a,b):
return a+b

x=int(input("Enter a number:"))
y=int(input("Enter another number:"))

s=sum(x,y)
print("Sum of two numbers:",s)

 The sample output would be –
Enter a number:3

Dept of ECE, BNMIT Page 9


Python Programming on Raspberry PI -22ECE136 Module II

Enter another number:4


Sum of two numbers: 7
 In the above example, The function sum() take two arguments and returns their sum to the receiving
variable s.
 When a function returns something and if it is not received using a LHS variable, then the return
value will not be available.
 For instance, in the above example if we just use the statement sum(x,y) instead of s=sum(x,y),
then the value returned from the function is of no use.
 On the other hand, if we use a variable at LHS while calling void functions, it will receive None.
For example,
p= test(var) #function used in previous example
print(p)
 Now, the value of p would be printed as None. Note that, None is not a string, instead it is of type
class 'NoneType'. This type of object indicates no value.

STRINGS
 A string is a sequence of characters, enclosed either within a pair of single quotes or double
quotes.
 Each character of a string corresponds to an index number, starting with zero as shown below:
S= “Hello World”

character H e l l o w o r l d
index 0 1 2 3 4 5 6 7 8 9 10

 The characters of a string can be accessed using index enclosed within square brackets.
 So, H is the 0th letter, e is the 1th letter and l is the 2th letter of “Hello world”
 For example,
>>> word1="Hello"
>>> word2='hi'
>>> x=word1[1] #2nd character of word1 is extracted
>>> print(x)
e
>>> y=word2[0] #1st character of word1 is extracted
>>> print(y)
h
 Python supports negative indexing of string starting from the end of the string as shown below:
S= “Hello World”

Dept of ECE, BNMIT Page 10


Python Programming on Raspberry PI -22ECE136 Module II

character H e l l o w o r l d
Negative index -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

 The characters can be extracted using negative index also, which count backward from the end of
the string.
 For example:
>>> var=“Hello”
>>> print(var[-1])
o
>>> print(var[-4])
e

 Whenever the string is too big to remember last positive index, one can use negative index to
extract characters at the end of string.

 Getting Length of a String using len()


 The len() function is a built-in function that can be used to get length of a string, which returns the
number of characters in a string
 Example:
>>> var="Hello"
>>> ln=len(var)
>>> print(ln)
5
 The index for string varies from 0 to length-1. Trying to use the index value beyond this range
generates error.
>>> var="Hello"
>>> ln=len(var)
>>> ch=var[ln]
IndexError: string index out of range

 Traversal through String with a Loop


 Extracting every character of a string one at a time and then performing some action on that
character is known as traversal.
 A string can be traversed either using while loop or using for loop in different ways. Few of such
methods is shown here –
 Using for loop:
st="Hello"
for i in st:
print(i, end='\t')
Dept of ECE, BNMIT Page 11
Python Programming on Raspberry PI -22ECE136 Module II

Output:
H e l l o

 In the above example, the for loop is iterated from first to last character of the string st. That is, in
every iteration, the counter variable i takes the values as H, e, l, l and o. The loop terminates when
no character is left in st.
 Using while loop:
st="Hello"
i=0
while i<len(st):
print(st[i], end=’\t’)
i+=1
Output:
H e l l o
 In this example, the variable i is initialized to 0 and it is iterated till the length of the string. In every
iteration, the value of i is incremented by 1 and the character in a string is extracted using i as index.
 Example: Write a while loop that starts at the last character in the string and traverses backwards to
the first character in the string, printing each letter on separate line
str="Hello"
i=-1
while i>=-len(str):
print(str[i])
i-=1
Output:
o
l
l
e
H

 String Slices
 A segment or a portion of a string is called as slice.
 Only a required number of characters can be extracted from a string using colon (:) symbol.
 The basic syntax for slicing a string would be – st[i:j:k]
 This will extract character from ith character of st till (j-1)th character in steps of k.
 If first index is not present, it means that slice should start from the beginning of the string. I
 f the second index j is not mentioned, it indicates the slice should be till the end of the string.
 The third parameter k, also known as stride, is used to indicate number of steps to be incremented
after extracting first character. The default value of stride is 1.

Dept of ECE, BNMIT Page 12


Python Programming on Raspberry PI -22ECE136 Module II

 Consider following examples along with their outputs to understand string slicing.
st="Hello World" #refer this string for all examples

1. print("st[:] is", st[:]) #output Hello World


As both index values are not given, it assumed to be a full string.
2. print("st[0:5] is ", st[0:5]) #output is Hello
th th
Starting from 0 index to 4 index (5 is exclusive), characters will be printed.
3. print("st[0:5:1] is", st[0:5:1]) #output is Hello
This code also prints characters from 0th to 4th index in the steps of 1. Comparing this example
with previous example, we can make out that when the stride value is 1, it is optional to
mention.

4. print("st[3:8] is ", st[3:8]) #output is lo Wo


rd th
Starting from 3 index to 7 index (8 is exclusive), characters will be printed.

5. print("st[7:] is ", st[7:]) #output is orld


th
Starting from 7 index to till the end of string, characters will be printed.

6. print(st[::2]) #output is HloWrd


This example uses stride value as 2. So, starting from first character, every alternative character
(char+2) will be printed.

7. print("st[4:4] is ", st[4:4]) #gives empty string


Here, st[4:4] indicates, slicing should start from 4th character and end with (4-1)=3rd character,
which is not possible. Hence the output would be an empty string.

8. print(st[3:8:2]) #output is l o
Starting from 3rd character, till 7th character, every alternative index is considered.

9. print(st[1:8:3]) #output is eoo


Starting from index 1, till 7 index, every 3rd character is extracted here.
th

10. print(st[-4:-1]) #output is orl


Refer the diagram of negative indexing given earlier. Excluding the -1st character, all
characters at the indices -4, -3 and -2 will be displayed. Observe the role of stride with default
value 1 here. That is, it is computed as -4+1 =-3, -3+1=-2 etc.

11. print(st[-1:]) #output is d


Here, starting index is -1, ending index is not mentioned (means, it takes the index 10) and the
stride is default value 1. So, we are trying to print characters from -1 (which is the last character

Dept of ECE, BNMIT Page 13


Python Programming on Raspberry PI -22ECE136 Module II

of negative indexing) till 10th character (which is also the last character in positive indexing) in
incremental order of 1. Hence, we will get only last character as output.

12. print(st[:-1]) #output is Hello Worl


Here, starting index is default value 0 and ending is -1 (corresponds to last character in
negative indexing). But, in slicing, as last index is excluded always, -1st character is omitted and
considered only up to -2nd character.

13. print(st[::]) #outputs Hello World


Here, two colons have used as if stride will be present. But, as we haven’t mentioned stride its
default value 1 is assumed. Hence this will be a full string.

14. print(st[::-1]) #output is dlroW olleH


This example shows the power of slicing in Python. Just with proper slicing, we could able to
reverse the string. Here, the meaning is a full string to be extracted in the order of -1. Hence,
the string is printed in the reverse order.

15. print(st[::-2]) #output is drWolH


Here, the string is printed in the reverse order in steps of -2. That is, every alternative character
in the reverse order is printed. Compare this with example (6) given above.

By the above set of examples, one can understand the power of string slicing and of Python script. The
slicing is a powerful tool of Python which makes many task simple pertaining to data types like strings,
Lists, Tuple, Dictionary etc. (Other types will be discussed in later Modules)

 Strings are Immutable


 The objects of string class are immutable.
 That is, once the strings are created (or initialized), they cannot be modified.
 No character in the string can be edited/deleted/added.
 Instead, one can create a new string using an existing string by imposing any modification
required.
 Try to attempt following assignment –
>>> st= “Hello World”
>>> st[3]='t'
TypeError: 'str' object does not support item assignment
 The error message clearly states that an assignment of new item („t‟) is not possible on string
object(st).
 The reason for this is strings are immutable
 So, to achieve our requirement, we can create a new string using slices of existing string as below

Dept of ECE, BNMIT Page 14


Python Programming on Raspberry PI -22ECE136 Module II

>>> st= “Hello World”


>>> st1= st[:3]+ 't' + st[4:]
>>> print(st1)
Helto World # l is replaced by t in new string st1
 Looping and Counting
 Using loops on strings, we can count the frequency of occurrence of a character within another
string.
 The following program demonstrates such a pattern on computation called as a counter.
 Initially, we accept one string and one character (single letter). Our aim to find the total number of
times the character has appeared in string.
 A variable count is initialized to zero, and incremented each time „a‟ character is found. The
program is given below –
word="banana"
count=0
for letter in word:
if letter =='a':
count=count+1
print("The occurrences of character 'a' is %d "%(count))
Output:
The occurrences of character 'a' is 3
 Encapsulate the above code in a function named count and generalize it so that it accepts the string
and the letter as arguments

def count(st,ch):
cnt=0
for i in st:
if i==ch:
cnt+=1
return cnt

st=input("Enter a string:")
ch=input("Enter a character to be counted:")
c=count(st,ch)
print("%s appeared %d times in %s"%(ch,c,st))
Output:
Enter a string: hello how are you?
Enter a character to be counted: h
h appeared 2 times in hello how are you?

Dept of ECE, BNMIT Page 15


Python Programming on Raspberry PI -22ECE136 Module II

 The in Operator
 The in operator of Python is a Boolean operator which takes two string operands.
 It returns True, if the first operand appears as a substring in second operand, otherwise returns
False.
 For example,

>>> 'el' in 'hello' #el is found in hello


True
>>> 'x' in 'hello' #x is not found in hello
False

 String Comparison
 Basic comparison operators like < (less than), > (greater than), == (equals) etc. can be applied on
string objects.
 Such comparison results in a Boolean value True or False.
 Internally, such comparison happens using ASCII codes of respective characters.
 Consider following examples –

Ex1. st= “hello”


if st== ‘hello’:
print(‘same’)

Output is same. As the value contained in st and hello both are same, the equality results in True.

Ex2. st= “hello”


if st<= ‘Hello’:
print(‘lesser’)
else:
print(‘greater’)

Output is greater. The ASCII value of h is greater than ASCII value of H. Hence, hello
is greater than Hello.
NOTE: A programmer must know ASCII values of some of the basic characters. Here are few –
A–Z : 65 – 90
a–z : 97 – 122
0–9 : 48 – 57
Space 32
Enter Key 13

Dept of ECE, BNMIT Page 16


Python Programming on Raspberry PI -22ECE136 Module II

 String Methods
 String is basically a class in Python.
 When we create a string in program, an object of that class will be created.
 A class is a collection of member variables and member methods (or functions).
 When we create an object of a particular class, the object can use all the members (both variables
and methods) of that class.
 Python provides a rich set of built-in classes for various purposes. Each class is enriched with a
useful set of utility functions and variables that can be used by a Programmer.
 A programmer can create a class based on his/her requirement, which are known as user-defined
classes.
 The built-in set of members of any class can be accessed using the dot operator as shown–
objName.memberMethod(arguments)
 The dot operator always binds the member name with the respective object name. This is very
essential because, there is a chance that more than one class has members with same name. To
avoid that conflict, almost all Object oriented languages have been designed with this common
syntax of using dot operator.
 Python provides a function (or method) dir to list all the variables and methods of a particular class
object. Observe the following statements –

>>> s="hello" # string object is created with the name s


>>> type(s) #checking type of s
<class „str‟> #s is object of type class str
>>> dir(s) #display all methods and variables of object s

[' add ', ' class ', ' contains ', ' delattr ', ' dir ', ' doc ', ' eq ', ' format ', ' ge ', ' getattribute ',
' getitem ', ' getnewargs ', ' gt ', ' hash ', ' init ', ' init_subclass ', ' iter ', ' le ', ' len ', ' lt ',
' mod ', ' mul ', ' ne ', ' new ', ' reduce ', ' reduce_ex ', ' repr ', ' rmod ', ' rmul ', ' setattr
', ' sizeof ', ' str ', ' subclasshook ', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith',
'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind',
'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']

 Note that, the above set of variables and methods are common for any object of string class that
we create.
 Each built-in method has a predefined set of arguments and return type.
 To know the usage, working and behavior of any built-in method, one can use the command help.
 For example, if we would like to know what is the purpose of islower() function (refer above list

Dept of ECE, BNMIT Page 17


Python Programming on Raspberry PI -22ECE136 Module II

to check its existence!!), how it behaves etc, we can use the statement –
>>> help(str.islower)
Help on method_descriptor:
islower(...)
S.islower() -> bool

Return True if all cased characters in S are lowercase and if there is at least one upper
cased character in S, returns False otherwise.

 This is built-in help-service provided by Python. Observe the className.memberName format


while using help.
 The methods are usually called using the object name. This is known as method invocation. We
say that a method is invoked using an object.
 Now, we will discuss some of the important methods of string class.
 capitalize(s) : This function takes one string argument s and returns a capitalized version of that
string. That is, the first character of s is converted to upper case, and all other characters to
lowercase. Observe the examples given below –
Ex1. >>> s="hello"
>>> s1=str.capitalize(s)
>>> print(s1)
Hello #1st character is changed to uppercase

Ex2. >>> s="hello World"


>>> s1=str.capitalize(s)
>>> print(s1)
Hello world

Observe in Ex2 that the first character is converted to uppercase, and an in-between uppercase
letter W of the original string is converted to lowercase.
 s.upper(): This function returns a copy of a string s to uppercase. As strings are immutable, the
original string s will remain same.

>>> st= “hello”


>>> st1=st.upper()
>>> print(st1)
'HELLO'
>>> print( st) #no change in original string
'hello'
 s.lower(): This method is used to convert a string s to lowercase. It returns a copy of original string
after conversion, and original string is intact.

Dept of ECE, BNMIT Page 18


Python Programming on Raspberry PI -22ECE136 Module II

>>> st='HELLO'
>>> st1=st.lower()
>>> print(st1) hello
>>> print(st) #no change in original string
HELLO

 s.find(s1) : The find() function is used to search for a substring s1 in the string s. If found, the
index position of first occurrence of s1 in s, is returned. If s1 is not found in s, then -1 is returned.
>>> st='hello'
>>> i=st.find('l')
>>> print(i) #output is 2
>>> i=st.find('lo')
>>> print(i) #output is 3
>>> print(st.find(‘x’)) #output is -1
The find() function can take one more form with two additional arguments viz. start and end positions
for search.
>>> st="calender of Feb. cal of march"
>>> i= st.find(‘cal’)
>>> print(i) #output is 0
Here, the substring „cal‟is found in the very first position of st, hence the result is 0.
>>> i=st.find('cal',10,20)
>>> print(i) #output is 17
Here, the substring cal is searched in the string st between 10th and 20th position and hence the result
is 17.
>>> i=st.find('cal',10,15)
>>> print(i) #output is -1

In this example, the substring 'cal' has not appeared between 10th and 15th character of st. Hence,
the result is -1.

 s.strip(): Returns a copy of string s by removing leading and trailing white spaces.

>>> st=" hello world "


>>> st1 = st.strip()
>>> print(st1)
OUTPUT: hello world
The strip() function can be used with an argument chars, so that specified chars are removed from
beginning or ending of s as shown below –
>>> st="###Hello##"
>>> st1=st.strip('#')
Dept of ECE, BNMIT Page 19
Python Programming on Raspberry PI -22ECE136 Module II

>>> print(st1) #all hash symbols are removed


OUTPUT: Hello
We can give more than one character for removal as shown below –
>>> st="Hello world"
>>> st1=st.strip("Hld")
OUTPUT: ello wor
 S.startswith(prefix, start, end): This function has 3 arguments of which start and end are option.
This function returns True if S starts with the specified prefix, False otherwise.
>>> st="hello world"
>>> st.startswith("he") #returns True
When start argument is provided, the search begins from that position and returns True or False based
on search result.
>>> st="hello world"
>>> st.startswith("w",6) #True because w is at 6th position
When both start and end arguments are given, search begins at start and ends at end.
>>> st="xyz abc pqr ab mn gh”
>>> st.startswith("pqr ab mn",8,12) #returns False
>>> st.startswith("pqr ab mn",8,18) #returns True

The startswith() function requires case of the alphabet to match. So, when we are not sure about the
case of the argument, we can convert it to either upper case or lowercase and then use
startswith()function as below –
>>> st="Hello"
>>> st.startswith("he") #returns False
>>> st.lower().startswith("he") #returns True

 S.count(s1, start, end): The count() function takes three arguments – string, starting position and
ending position. This function returns the number of non-overlapping occurrences of substring s1 in
string S in the range of start and end.
>>> st="hello how are you? how about you?"
>>> st.count('h') #output is 3
>>> st.count(‘how’) #output is 2
>>> st.count(‘how’,3,10) #output is 1 because of range given

Example:
st=input("Enter a string:")
ch=input("Enter a character to be counted:")
c=st.count(ch)
print("%s appeared %d times in %s"%(ch,c,st))

Dept of ECE, BNMIT Page 20


Python Programming on Raspberry PI -22ECE136 Module II

 Parsing Strings
 Sometimes, we may want to search for a substring matching certain criteria.
 For example, finding domain names from email-Ids in the list of messages is a useful task in some projects.
 Consider a string below and we are interested in extracting only the domain name.

“From [email protected] Wed Feb 21 09:14:16 2018”

Now, aim is to extract only bnmit.ac.in, which is the domain name.


We can think of logic as–
o Identify the position of @, because all domain names in email IDs will be after the symbol @
o Identify a white space which appears after @ symbol, because that will be the end of domain
name.
o Extract the substring between @ and white-space.
The concept of string slicing and find() function will be useful here.
Consider the code given below –

st="From [email protected] Wed Feb 21 09:14:16 2018"


atpos=st.find('@') #finds the position of @

print('Position of @ is', atpos)


spacePos=st.find(‘ ‘, atpos) #position of white-space after @
print('Position of space after @ is', spacePos)
host=st[atpos+1:spacePos] #slicing from @ till white-space

print(host)

Output:
Position of @ is 10
Position of space after @ is 22
bnmit.ac.in

 Format Operator
 The format operator, % allows us to construct strings, replacing parts of the strings with the data stored in
variables.
 The first operand is the format string, which contains one or more format sequences that specify how the
second operand is formatted.
Syntax: “<format>” % (<values>)
 The result is a string.
>>> sum=20

Dept of ECE, BNMIT Page 21


Python Programming on Raspberry PI -22ECE136 Module II

>>> '%d' %sum


‘20’ #string ‘20’, but not integer 20
 Note that, when applied on both integer operands, the % symbol acts as a modulus operator. When the
first operand is a string, then it is a format operator.
 Consider few examples illustrating usage of format operator.

Ex1. >>> "The sum value %d is originally integer"%sum


'The sum value 20 is originally integer„

Ex2. >>> '%d %f %s'%(3,0.5,'hello')


'3 0.500000 hello’

Ex3. >>> '%d %g %s'%(3,0.5,'hello')


'3 0.5 hello’

Ex4. >>> '%d'% 'hello'


TypeError: %d format: a number is required, not str

Ex5. >>> '%d %d %d'%(2,5)


TypeError: not enough arguments for format string

**** ****

Dept of ECE, BNMIT Page 22

You might also like