Unit – 2
➢ The Structure of Strings - The Subscript Operator-Program using subscript operator-
Slicing for Substrings-Program for slicing substrings-Testing for a Substring with the in
Operator-Program using substring-The Positional System for Representing Numbers-Lab
4:Make a simple calculator -Converting binary to decimal-Program to convert binary to
decimal-Converting decimal to binary-Program to convert decimal to binary -String
Method-Program using string method-Octal and Hexadecimal Numbers-Text Files and
Their Format-Lab 5: Find the Factorial of a Number-Python Program to Convert Decimal
to Binary, Octal and Hexadecimal-Writing Text to a File-Writing Numbers to a File-
Reading Text from a File-Reading Numbers from a File-Example program to read and
write text and numbers-Accessing Files and Directories on Disk-Manipulating Files and
Directories on Disk-Example program to access and manipulate files-Lab 6: Program to
read and write text and numbers
The Structure of Strings
➢ String is a collection of alphabets, words or other characters.
➢ It is one of the primitive data structures and are the building blocks for data manipulation.
➢ Python has a built-in string class named str .
➢ Python strings are "immutable" which means they cannot be changed after they are created.
Creating Strings
➢ There are different ways in python to create strings like in single, double, as well as in
triple quotes.
➢ Ex:
s = 'Hello' #single quotes
s = 'It's raining outside' #syntax error(It confuses where string start and end)
s = "It's raining outside" #correct way
s = '''Good Morning''' #multi-line strings
➢ Triple quotes are used when you are declaring or accessing a large paragraph. There is an
in-built function for declaring or converting any other data type to string.
➢ a = 77 #int
➢ print(str(a)) #int to str
The Subscript Operator
The subscript operator
The subscript operator is defined as square brackets []. It is used to access the elements of string,
list tuple, and so on. Let's discuss the syntax with an example:
<given string>[<index>]
The given string is the string you want to examine and the index is the position of the character
you want to obtain. Let's discuss this with an example:
>>> name = "The Avengers">>> name[0]'T'>>> len(name)12>>> name[11]'s'>>> >>>
name[12] Traceback (most recent call last): File "<pyshell#6>", line 1, in <module>
name[12]IndexError: string index out of range>>>
The "The Avengers" string is 12 characters long, which means it ranges from 0 to 11 index.
The name[0] represents the character 'T'. If you give the 12th index value, ...
Program using subscript operator
String Slicing in Python
Since strings are a sequence of characters, you can access it through slicing and indexing just like
you would with Python lists or tuples. Strings are indexed with respect to each character in the
string and the indexing begins at 0:
In the string above, the first index is C and it is indexed 0. The last character is a full-
stop . which is the 16th character in the string. You can also access the characters in the opposite
direction starting from -1, which means you can also use -1 as an index value to access . in the
string. There is also a whitespace between Chocolate and cookie, this is also a part of the string
and has its own index, 9th in this case. You can check this using slicing.
Because each character in a Python string has a corresponding index number, you can access and
manipulate strings in the same ways as other sequential data types. Slicing is a technique in
Python that allow you to specific element or a sub-set of elements from a container object using
their index values. Slicing saves you from having to write loop statements to go through the
indexes of your string to find or access certain substrings.
snack = "Chocolate cookie."
print(snack[0])
print(snack[9])
print(snack[-1])
Common Functions:
These are the same functions that are available for all other iterator data types, including list,
tuple, set, and string.
1. length - It provides the string’s length.
2. minimum - This function returns the smallest character in a string, as determined by ASCII.
3. maximum - The largest character found in the string, as determined by ASCII, is provided
by the third option, maximum.
4. sorted - The string is sorted in either ascending or descending order using the ASCII
character sequence. This function always returns a list of characters as its result.
s = 'GoodMorning'
print(len(s))
print(min(s))
print(max(s))
print(sorted(s))
print(sorted(s, reverse = True))
output:
11
G
r
['G', 'M', 'd', 'g', 'i', 'n', 'n', 'o', 'o', 'o', 'r']
['r', 'o', 'o', 'o', 'n', 'n', 'i', 'g', 'd', 'M', 'G']
SOME SPECIFIC PURPOSE FUNCTIONS IN STRINGS
TITLE OR CAPITALIZE
The title function capitalizes the first letter of each word, whereas the capitalize function
capitalizes the first letter of a string.
s = "its raining outside"
print(s.capitalize()) #O / P - > Its raining outside
print(s.title()) #O / P - > Its Raining Outside
UPPER / LOWER / SWAP CASE
In string each character is converted in the upper function to lowercase characters. Swap case
changes an upper to a lower case character, and vice versa.
s = "Its Raining Outside"
print(s.upper()) #O / P - > ITS RAINING OUTSIDE
print(s.lower()) #O / P - > its raining outside
print(s.swapcase()) #O / P - > iTS rAINING oUTSIDE
COUNT
It provides the number of any substrings that are present in a string. It outputs 0 if the substring
is missing from the string. It is used to determine how often a given substring occurs in a string.
s = "Its Raining Outside"
print(s.count("i")) #3
print(s.count("ing")) # 1
FIND / INDEX
Both functions operate in exactly the same manner. Both locate the position of a substring within
a string. The sole distinction between the two functions is that while index gives an error when
the substring is absent, string find produces a negative value when this occurs.
s = "Its Raining Outside"
print(s.find("ing")) #8
print(s.index("ing")) # 8
print(s.find("down")) # - 1
print(s.index("down")) #error
Slicing for Substrings
Python slicing is about obtaining a sub-string from the given string by slicing it respectively
from start to end.
How String slicing in Python works
For understanding slicing we will use different methods, here we will cover 2 methods of
string slicing, the one is using the in-build slice() method and another using the [:] array slice.
String slicing in Python is about obtaining a sub-string from the given string by slicing it
respectively from start to end.
Python slicing can be done in two ways:
• Using a slice() method
• Using array slicing [ : : ] method
Index tracker for positive and negative index: String indexing and slicing in python. Here,
the Negative comes into consideration when tracking the string in reverse.
Method 1: Using slice() method
The slice() constructor creates a slice object representing the set of indices specified by
range(start, stop, step).
Syntax:
• slice(stop)
• slice(start, stop, step)
Parameters: start: Starting index where the slicing of object starts. stop: Ending index where
the slicing of object stops. step: It is an optional argument that determines the increment
between each index for slicing. Return Type: Returns a sliced object containing elements in
the given range only.
Example:
# String slicing
String = 'ASTRING'
# Using slice constructor
s1 = slice(3)
s2 = slice(1, 5, 2)
s3 = slice(-1, -12, -2)
print(String[s1])
print(String[s2])
print(String[s3])
Output:
AST
SR
GITA
Method 2: Using List/array slicing [ : : ] method
In Python, indexing syntax can be used as a substitute for the slice object. This is an easy and
convenient way to slice a string using list slicing and Array slicing both syntax-wise and
execution-wise. A start, end, and step have the same mechanism as the slice() constructor.
Below we will see string slicing in Python with example.
Syntax
arr[start:stop] # items start through stop-1
arr[start:] # items start through the rest of the array
arr[:stop] # items from the beginning through stop-1
arr[:] # a copy of the whole array
arr[start:stop:step] # start through not past stop, by step
Example 1:
In this example, we will see slicing in python list the index start from 0 indexes and ending
with a 2 index(stops at 3-1=2 ).
Example 2:
In this example, we will see the example of starting from 1 index and ending with a 5
index(stops at 3-1=2 ), and the skipping step is 2. It is a good example of Python slicing string
by character.
Exception handling in Python
Exception:
An Exception is an error that happens during the execution of a program. Whenever there is
an error, Python generates an exception that could be handled. It basically prevents the program
from getting crashed.
Common Examples of Exception:
• Division by Zero
• Accessing a file which does not exist.
• Addition of two incompatible types
• Trying to access a nonexistent index of a sequence
• Removing the table from the disconnected database server.
Exception handling
• Exception handling allows you to separate error-handling code from normal code.
• An exception is a Python object which represents an error.
• It clarifies the code and enhances readability.
try...except Block
The try...except block is used to handle exceptions in Python. Here's the syntax of try...except
block:
try:
# code that may cause exception
except:
# code to run when exception occurs
Here, we have placed the code that might generate an exception inside the try block. Every try
block is followed by an except block.
When an exception occurs, it is caught by the except block. The except block cannot be used
without the try block.
Ex.1:
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
# Output: Error: Denominator cannot be 0.
In the example, we are trying to divide a number by 0. Here, this code generates an exception.
To handle the exception, we have put the code, result = numerator/denominator inside the try
block. Now when an exception occurs, the rest of the code inside the try block is skipped.
The except block catches the exception and statements inside the except block are executed.
If none of the statements in the try block generates an exception, the except block is skipped.
Catching Specific Exceptions in Python
For each try block, there can be zero or more except blocks. Multiple except blocks allow us to
handle each exception differently.
The argument type of each except block indicates the type of exception that can be handled by it.
ArithmeticError Raised when an error occurs in numeric calculations
AssertionError Raised when an assert statement fails
AttributeError Raised when attribute reference or assignment fails
Exception Base class for all exceptions
EOFError Raised when the input() method hits an "end of file"
condition (EOF)
IndentationError Raised when indentation is not correct
IndexError Raised when an index of a sequence does not exist
KeyError Raised when a key does not exist in a dictionary
Built-in Exception
Ex:2
try:
even_numbers = [2,4,6,8]
print(even_numbers[5])
except ZeroDivisionError:
print("Denominator cannot be 0.")
except IndexError:
print("Index Out of Bound.")
# Output: Index Out of Bound
In this example, we have created a list named even_numbers.
Since the list index starts from 0, the last element of the list is at index 3. Notice the statement,
print(even_numbers[5])
Here, we are trying to access a value to the index 5. Hence, IndexError exception occurs.
When the IndexError exception occurs in the try block,
The ZeroDivisionError exception is skipped.
The set of code inside the IndexError exception is executed.
Python try with else clause
In some situations, we might want to run a certain block of code if the code block inside try runs
without any errors.
For these cases, you can use the optional else keyword with the try statement.
Ex_3
# program to print the reciprocal of even numbers
try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1/num
print(reciprocal)
Output
If we pass an odd number:
Enter a number: 1
Not an even number!
If we pass an even number, the reciprocal is computed and displayed.
Enter a number: 4
0.25
However, if we pass 0, we get ZeroDivisionError as the code block inside else is not handled by
preceding except.
Enter a number: 0
Traceback (most recent call last):
File "<string>", line 7, in <module>
reciprocal = 1/num
ZeroDivisionError: division by zero
Note: Exceptions in the else clause are not handled by the preceding except clauses.
Python try...finally
In Python, the finally block is always executed no matter whether there is an exception or not.
The finally block is optional. And, for each try block, there can be only one finally block.
Ex_4
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
finally:
print("This is finally block.")
Output
Error: Denominator cannot be 0.
This is finally block.
In the above example, we are dividing a number by 0 inside the try block. Here, this code
generates an exception.
The exception is caught by the except block. And, then the finally block is executed.
Python Custom Exceptions
Sometimes we may need to create our own custom exceptions that serve our purpose.
Defining Custom Exceptions
Here's the syntax to define custom exceptions,
class CustomError(Exception):
...
pass
try:
...
except CustomError:
...
Here, CustomError is a user-defined error which inherits from the Exception class.
Note:
When we are developing a large Python program, it is a good practice to place all the user-
defined exceptions that our program raises in a separate file.
Many standard modules define their exceptions separately as exceptions.py or errors.py
(generally but not always).
EX-5
Example: Python User-Defined Exception
# define Python user-defined exceptions
class InvalidAgeException(Exception):
"Raised when the input value is less than 18"
pass
# you need to guess this number
number = 18
try:
input_num = int(input("Enter a number: "))
if input_num < number:
raise InvalidAgeException
else:
print("Eligible to Vote")
except InvalidAgeException:
print("Exception occurred: Invalid Age")
Output
If the user input input_num is greater than 18,
Enter a number: 45
Eligible to Vote
If the user input input_num is smaller than 18,
Enter a number: 14
Exception occurred: Invalid Age
In the above example, we have defined the custom exception InvalidAgeException by creating a
new class that is derived from the built-in Exception class.
Here, when input_num is smaller than 18, this code generates an exception.
When an exception occurs, the rest of the code inside the try block is skipped.
The except block catches the user-defined InvalidAgeException exception and statements inside
the except block are executed.
Lambda function in python
Lambda Functions in Python are anonymous functions, implying they don't have a name. The
def keyword is needed to create a typical function in Python, as we already know. We can also
use the lambda keyword in Python to define an unnamed function.
Syntax of Python Lambda Function
lambda arguments: expression
This function accepts any count of inputs but only evaluates and returns one expression.
Lambda functions can be used whenever function arguments are necessary. In addition to other
forms of formulations in functions, it has a variety of applications in certain coding domains. It's
important to remember that according to syntax, lambda functions are limited to a single
statement.
example of Lambda Function in Python
An example of a lambda function that adds 4 to the input number is shown below.
Code to demonstrate how we can use a lambda function
add = lambda num: num + 4
print( add(6) )
Output:10
The lambda function is "lambda num: num+4" in the given programme. The parameter is num,
and the computed and returned equation is num * 4.
There is no label for this function. It generates a function object associated with the "add"
identifier. We can now refer to it as a standard function. The lambda statement, "lambda num:
num+4", is nearly the same as:
Code
def add( num ):
return num + 4
print( add(6) )
Output:10
What's the Distinction Between Lambda and Def Functions?
Let's glance at this instance to see how a conventional def defined function differs from a
function defined using the lambda keyword. This program calculates the reciprocal of a given
number:
Code
# Python code to show the reciprocal of the given number to highlight the difference between
def() and lambda().
def reciprocal( num ):
return 1 / num
lambda_reciprocal = lambda num: 1 / num
# using the function defined by def keyword
print( "Def keyword: ", reciprocal(6) )
# using the function defined by lambda keyword
print( "Lambda keyword: ", lambda_reciprocal(6) )
Output:
Def keyword: 0.16666666666666666
Lambda keyword: 0.16666666666666666
The reciprocal() and lambda_reciprocal() functions act similarly and as expected in the preceding
scenario. Let's take a closer look at the sample above:
Both of these yield the reciprocal of a given number without employing Lambda. However, we
wanted to declare a function with the name reciprocal and send a number to it while executing
def. We were also required to use the return keyword to provide the output from wherever the
function was invoked after being executed.
Using Lambda: Instead of a "return" statement, Lambda definitions always include a statement
given at output. The beauty of lambda functions is their convenience. We need not allocate a
lambda expression to a variable because we can put it at any place a function is requested.
Using Lambda Function with map()
A method and a list are passed to Python's map() function.
The function is executed for all of the elements within the list, and a new list is produced with
elements generated by the given function for every item.
The map() method is used to square all the entries in a list in this example.
Code
#Code to calculate the square of each number of a list using the map() function
numbers_list = [2, 4, 5, 1, 3, 7, 8, 9, 10]
squared_list = list(map( lambda num: num ** 2 , numbers_list ))
print( squared_list )
Output:
[4, 16, 25, 1, 9, 49, 64, 81, 100]
Using Lambda Function with List Comprehension
We'll apply the lambda function combined with list comprehension and lambda keyword with a
for loop in this instance. We'll attempt to print the square of numbers in the range 0 to 11.
Code
#Code to calculate square of each number of list using list comprehension
squares = [lambda num = num: num ** 2 for num in range(0, 11)]
for square in squares:
print( square(), end = " ")
Output:
0 1 4 9 16 25 36 49 64 81 100
Using Lambda Function with if-else
We will use the lambda function with the if-else block.
Code
# Code to use lambda function with if-else
Minimum = lambda x, y : x if (x < y) else y
print(Minimum( 35, 74 ))
Output:35