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

Unit 2 Exception in python-1

This document covers Exception Handling in Python, explaining the difference between errors and exceptions, and how to manage them using try and except statements. It also discusses various types of exceptions, the use of else and finally clauses, and the creation and calling of functions, including default arguments and command line arguments. Additionally, it highlights the importance of built-in library functions and user-defined functions in Python programming.

Uploaded by

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

Unit 2 Exception in python-1

This document covers Exception Handling in Python, explaining the difference between errors and exceptions, and how to manage them using try and except statements. It also discusses various types of exceptions, the use of else and finally clauses, and the creation and calling of functions, including default arguments and command line arguments. Additionally, it highlights the importance of built-in library functions and user-defined functions in Python programming.

Uploaded by

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

Divya S R, Assistant Professor, AESNC, Gauribidanur.

Unit-2

Unit 2
Exception Handling

Exception Handling
Exceptions are raised when the program is syntactically correct, but the
code resulted in an error. This error does not stop the execution of the
program, however, it changes the normal flow of the program.

Example
# initialize the amount variable
marks = 10000
# perform division with 0
a = marks / 0
print(a)

Output:

Some of the common built-in exceptions mentioned below exceptions


are:

Exception Description
IndexError When the wrong index of a list is retrieved.
AssertionError It occurs when the assert statement fails
AttributeError It occurs when an attribute assignment is failed.
ImportError It occurs when an imported module is not found.
KeyError It occurs when the key of the dictionary is not found.
NameError It occurs when the variable is not defined.
MemoryError It occurs when a program runs out of memory.
It occurs when a function and operation are applied in
TypeError
an incorrect type.

II BCA, IV sem Python Programming


1
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Errors in Python
Errors are the problems in a program due to which the program will stop
the execution. On the other hand, exceptions are raised when some
internal events occur which changes the normal flow of the program.

Two types of Error occurs in python.


1. Syntax errors
2. Logical errors (Exceptions)

1) Syntax errors
When the proper syntax of the language is not followed then a syntax
error is thrown.
Example
# initialize the amount variable
amount = 10000
# check that You are eligible to
# purchase Python Software or not
if(amount>2999)
print("You are eligible to purchase Python Software ")

Output:

II BCA, IV sem Python Programming


2
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

2) logical errors(Exception)
When in the runtime an error that occurs after passing the syntax test is
called exception or logical type.
For example, when we divide any number by zero then the
“ZeroDivisionError” exception is raised, or when we import a module
that does not exist then “ImportError” is raised.

Example
# initialize the amount variable
marks = 10000
# perform division with 0
a = marks / 0
print(a)

Output:

In the above example the “ZeroDivisionError” as we are trying to divide


a number by 0.

Exception Handling
When an error and an exception are raised then we handle that with the
help of the Handling method.
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.

II BCA, IV sem Python Programming


3
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Try and Except Statement – Catching Exceptions


Try and except statements are used to catch and handle exceptions in
Python. Statements that can raise exceptions are kept inside the try clause
and the statements that handle the exception are written inside except
clause.

Example: Let us try to access the array element whose index is out of
bound and handle the corresponding exception.

# Python program to handle simple runtime error

a = [1, 2, 3]

try:
print ("Second element = %d" %(a[1]))
# Throws error since there are only 3 elements in array
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")

Output:
Second element = 2
An error occurred

 In the above example, the statements that can cause the error are
placed inside the try statement (second print statement in our
case).
 The second print statement tries to access the fourth element of the
list which is not there and this throws an exception.
 This exception is then caught by the except statement.

II BCA, IV sem Python Programming


4
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Catching Specific Exception


A try statement can have more than one except clause, to specify
handlers for different exceptions. Please note that at most one handler
will be executed. For example, we can add Index Error in the above
code.

The general syntax for adding specific exceptions are –

try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)

Example:
#Program for multiple catch statement
# Program to handle multiple errors with one
# except statement
def fun(a):
if a < 4:
# throws ZeroDivisionError for a = 3
b = a/(a-3)
# throws NameError if a >= 4
print("Value of b = ", b)
try:
fun(3)
fun(5)

II BCA, IV sem Python Programming


5
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

# note that braces () are necessary here for


# multiple exceptions
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")

Output
ZeroDivisionError Occurred and Handled
If you comment on the line fun(3), the output will be
NameError Occurred and Handled

Try with Else Clause


In python, you can also use the else clause on the try-except block which
must be present after all the except clauses. The code enters the else
block only if the try clause does not raise an exception.
Example
# Program to depict else clause with try-except
# Function which returns a/b
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
# Driver program to test above function
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
Output:
-5.0
a/b result in 0

II BCA, IV sem Python Programming


6
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Finally Keyword in Python


Python provides a keyword finally, which is always executed after the try
and except blocks. The final block always executes after normal termination
of try block or after try block terminates due to some exception.
Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)

Example:
# Python program to demonstrate finally
# No exception Exception raised in try block
try:
k = 5//0 # raises divide by zero exception.
print(k)
# handles zerodivision exception
except ZeroDivisionError:
print("Can't divide by zero")
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Output:
Can't divide by zero
This is always executed

II BCA, IV sem Python Programming


7
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Python Functions
Python Functions is a block of statements that return the specific task.
The idea is to put some commonly or repeatedly done tasks together
and make a function so that instead of writing the same code again and
again for different inputs, we can do the function calls to reuse code
contained in it over and over again.

General syntax is

def function_name(arguments):
# function body
return

 def - keyword used to declare a function


 function_name - any name given to the function
 arguments - any value passed to function
 return (optional) - returns value from a function

Example
def greet():
print('Hello World!')

Here, we have created a function named greet(). It simply prints the text
Hello World!.

II BCA, IV sem Python Programming


8
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Creating a Python Function


We can create a Python function using the def keyword.

Example
# A simple Python function

def fun():

print("Welcome to AESNC")

calling a Function
After creating a function we can call it by using the name of the function
followed by parenthesis containing parameters of that particular function.
Example:
# A simple Python function
def fun():
print("Welcome to AESNC")
# Driver code to call a function
fun()

Output:
Welcome to AESNC

The return Statement in Python


A Python function may or may not return a value. If we want our function
to return some value to a function call, we use the return statement. For

example,
def add_numbers():
....................
return sum
Here, we are returning the variable sum to the function call.

II BCA, IV sem Python Programming


9
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Example
# function definition
def find_square(num):
result = num * num
return result
# function call
square = find_square(3)
print('Square:',square)

Output: Square: 9

The following example has a function with one argument (fname).


When the function is called, we pass along a first name, which is used
inside the function to print the full name:

def my_function(fname): #fname is the argument or parameter


print(fname + " ABC")
my_function("Emil")
my_function("Tobias")
my_function("Linus")

Output
Emil ABC
Tobias ABC
Linus ABC

II BCA, IV sem Python Programming


10
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Python Function Arguments


As mentioned earlier, a function can also have arguments. An argument is
a value that is accepted by a function.

Example
# function with two arguments
def add_num(num1, num2):
sum = num1 + num2
print('Sum: ',sum)
# function with no argument
def add_num():

If we create a function with arguments, “we need to pass the


corresponding values while calling them”.

Example
# function call with two values
add_num(5, 4)
# function call with no value
add_num()

Combine using function with arguments


# function with two arguments
def add_num()
(num1, num2):
sum = num1 + num2
print("Sum: ",sum)
# function call with two values
add_num(5, 4)

Output:
Sum: 9

II BCA, IV sem Python Programming


11
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Python parameters
Parameters in python are variables — placeholders for the actual
values the function needs. When the function is called, these values
are passed in as arguments.
For example, the arguments passed into the function

The general syntax is


def function_name(parameter: data_type) -> return_type:

"""Docstring"""
# body of the function

return expression

Python Library Functions


In Python, standard library functions are the built-in functions that can be
used directly in our program. For example,
 print() - prints the string inside the quotation marks
 sqrt() - returns the square root of a number
 pow() - returns the power of a number

These library functions are defined inside the module. And, to use them
we must include the module inside our program.

Types of Function
There are two types of function in Python programming:
 Standard library functions - These are built-in functions in
Python that are available to use.
 User-defined functions - We can create our own functions based
on our requirements.

II BCA, IV sem Python Programming


12
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Default arguments
In Python, we can provide default values to function arguments. We use
the ” = “ Assignment operator to provide default values.
In other words, Default values indicate that the function argument will
take that value if no argument value is passed during the function call.
The default value is assigned by using the assignment(=) operator of the
form ”keywordname=value“.

Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function() #It will take default values i.e Norway
my_function("Brazil")

Output
I am from Sweden
I am from India
I am from Norway
I am from Brazil

Command Line Arguments


 It is the another way to accept the “inputs” other than input().
 Inputs will be passed to the program as an arguments from
command prompt.
 For the processing of inputs we have to use the “sys module” in
the command prompts.
 All the arguments which used to passed to the command prompts it
will forms a list i.e a python LIST as argv(argument value).

II BCA, IV sem Python Programming


13
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

 This will be access by using sys.argv we can access the command


prompts.
 In python every arguments is passing to the List in the format of
input is string.
 Elements of argv can be accessed using INDEX .The index will be
starts from zero (0).
 Always sys.argv[0] should be a file name.
sys.argv[1]
sys.argv[2]
………………….
………………….
sys.argv[n]
Therefore 1,2,……,n are the arguments.
 In our program compulsory we have to import the sys module
before using the argv.

Python provides various ways of dealing with these types of arguments.


The three most common are:
 Using sys.argv
 Using getopt module
 Using argparse module

 sys.argv
In python sys module stores the command line arguments into a list, we
can access it using sys.argv. This is very useful and simple way to read
command line arguments as String.

Note: argument count (argc), while argument value (argv).

import sys #first we have to write this before starting the program
print (sys.argv) #we have to access the elements i.e arguments printed in
#the program

II BCA, IV sem Python Programming


14
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

len(sys.argv) #gives the length of the arguments including file name

Steps to execute the program


 Write a program
 Save the filename i.e “filename.py”
 Open RUN type the cmd..
 Command prompt window will display
 Change the path where the program being is to saved.
 Use the “py” followed by “filename.py” Arg1 Arg2 Arg3 ………
Note: we should not give comma as mentioned above in Arg1 Arg2
Arg3 …….
 py filename.py Arg1 Arg2 Arg3 these are the inputs passed
into the argv.

Working
 Write a program in python IDE.Save a file in python folder as
cmd.py
Example: import sys
Print (sys.argv)
 Go with the command prompt and paste the location of the file.

II BCA, IV sem Python Programming


15
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

 Press an enter and type the file name as cmd.py 1 2 3 4 5.

 Output looks like


[‘cmd.py’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’ ]
 Using argv it will call the arguments.
 Again if we want to find the length of the argv then we have to
write as
Example: import sys
print (sys.argv)
print(len(system.argv))
Output

It will display as
[‘cmd.py’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’ ]
6
II BCA, IV sem Python Programming
16
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Note: 6 is the length of the arguments.

Again we can also print the values using looping


Example: import sys
print (sys.argv)
print(len(system.argv))
for ele in sys.argv:
print (“Argument:”,ele)
output:

 getopt()
The getopt module helps us parse the options and operands that are
provided to our program on the command line. This module has one very
important function, also named getopt.

Syntax:
getopt.getopt( args , options ,< long_options>) → ( options, operands )

II BCA, IV sem Python Programming


17
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

 args is the argument list to be passed. The args value should not
include sys.argv[0], the program name. Therefore, the argument
value for args is almost always sys.argv[1:].
 options is the string of options letter that the script wants to
recognize.
 long_options is the list of strings with names of the long options
which should be supported.
It returns the list of (option, value/operands) pairs and list of program
arguments left after the option list was stripped.

Example
import sys
import getopt

def full_name():
first_name = None
last_name = None
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, "f:l:")

except:
print("Error")

for opt, arg in opts:


if opt in ['-f']:
first_name = arg
elif opt in ['-l']:
last_name = arg

print( first_name +" " + last_name)

full_name()

II BCA, IV sem Python Programming


18
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

output:

argparse
 The argparse module makes it easy to write user-friendly
command-line interfaces. It parses the defined arguments from the
sys.argv.
 The argparse module also automatically generates help and usage
messages, and issues errors when users give the program invalid
arguments.
 The argparse is a standard module; we do not need to install it.
 A parser is created with ArgumentParser and a new parameter is
added with add_argument. Arguments can be optional, required,
or positional.

Key word argument


In Python, the terms parameter and argument are used
interchangeably. However, there is a slight distinction between these
two terms.
Parameters are the input variables bounded by parentheses when
defining a function.
Arguments are the values assigned to these parameters when
passed into a function (or method) during a function call.

Example

def team(name, surname):

print(name, "is working on an", project)

team("Divya", "Setty")

II BCA, IV sem Python Programming


19
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

In the example above, the function arguments are Divya and Setty,
whereas name and surname are the function parameters.

Types of Arguments
There are two types of arguments:
 positional arguments
 keyword arguments.

Positional arguments
 Positional arguments are values that are passed into a function
based on the order in which the parameters were listed during the
function definition.
 Here, the order is especially important as values passed into these
functions are assigned to corresponding parameters based on their
position.

Example

def team(name, working):

print(name, "is working as a ", project)

team("Ram", "Assistant Professor")

Output:
Ram is working as an Assistant Professor

 Keyword arguments
Keyword arguments (or named arguments) are values that, when passed
into a function, are identifiable by specific parameter names. A keyword
argument is preceded by a parameter and the assignment operator, = .

II BCA, IV sem Python Programming


20
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Example
def team(name, project):
print(name, "is working on an", project)
team(project = "Edpresso", name = 'FemCode')

Output:
FemCode is working on an Edpresso

Recursive Functions
“Recursion is the process of defining something in terms of itself”.
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.

II BCA, IV sem Python Programming


21
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Example

def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))

Output

The factorial of 3 is 6

Note:
 To create strings that span multiple lines, triple single quotes '''.
 Triple double quotes """ are used to enclose the string.

Scope and Lifetime of Variables in Functions.


The scope is nothing but the visibility of variables and Lifetime is
nothing but the duration which variable is exist.

There are two primary scopes of variables in Python:


 Local variable
 Global variable
 Nonlocal Variables

 Local Variable
Local Variables inside a function in Python
 In the local variable, we will declare the variable inside the function.
 Here funt() is the function name.
 ‘x’ is the variable.

II BCA, IV sem Python Programming


22
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

For example
def funt(): //it is function
x='hello local variable' //variable inside function
print(x)
funt() //here it is function call

output
hello local variable

 Global Variable
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
# declare global variable
message = 'Hello'
def greet():
# declare local variable
print('Local', message)
greet()
print('Global', message)

Output
Local Hello
Global Hello

II BCA, IV sem Python Programming


23
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

 Nonlocal Variables
In Python, 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.
We use the nonlocal keyword to create nonlocal variables.

For example
# outside function
def outer():
message = 'local'

# nested function
def inner():

# declare nonlocal variable


nonlocal message

message = 'nonlocal variable'


print("inner:", message)

inner()
print("outer:", message)

outer()

output
inner: nonlocal variable
outer: nonlocal variable

In the above example, there is a nested inner() function. We have used


the nonlocal keywords to create a nonlocal variable.
The inner() function is defined in the scope of another function outer().

II BCA, IV sem Python Programming


24
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Strings
Definition
Strings in python are surrounded by either single quotation marks, or
double quotation marks. 'hello' is the same as "hello".
Example
#You can use double or single quotes:
print("Hello")
print('Hello')

Output:
Hello
Hello

Creating a String in Python


Strings in Python can be created using single quotes or double
quotes or even triple quotes.

Example
#Using single quotes
str1 = 'Hello Python'
print(str1)
#Using double quotes
str2 = "Hello Python"
print(str2)
#Using triple quotes
str3 = “”””Triple quotes are generally used for
represent the multiline or
docstring”””
print(str3)

II BCA, IV sem Python Programming


25
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring

Note:
Multiline String
We can also create a multiline string in Python. For this, we use triple
double quotes """ or triple single quotes '''. For example,
Example
# multiline string
message = """
Never gonna give you up
Never gonna let you down
"""
print(message)

Output
Never gonna give you up
Never gonna let you down

Strings are immutable: In Python, strings are immutable. That means


the characters of a string cannot be changed.
Example
message = 'Hola Amigos'
# assign new string to message variable
message = 'Hello Friends'
prints(message);
Output
Hello Friends
II BCA, IV sem Python Programming
26
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Accessing String Characters


We can access the characters in a string in three ways.
 Indexing: One way is to treat strings as a list and use index
values.

For example
greet = 'hello'
# access 1st index element
print(greet[1])

Output:
e

 Negative Indexing: The index of -1 refers to the last item, -2 to


the second last item and so on.

For example 1
greet = 'hello'
# access 4th last element
print(greet[-4])

Output:
e

Example 2
str = 'Hellow World!'
print(str [0:-6]) # output is Hellow
print(str [7:-1]) # output is World

II BCA, IV sem Python Programming


27
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

 Slicing: Access a range of characters in a string by using the slicing


operator colon ” : “.

Example
greet = 'Hello'
# access character from 1st index to 3rd index
print(greet[1:4])

output
ell

Some more example for accessing character


str = 'Hellow World!'
print(str [0]) # output is "H"
print(str [7]) # output is "W"
print(str [0:6]) #output is Hellow
print(str [7:12]) #output is World

The str() function


The str() method returns the string representation of a given object.

Syntax
str(object, encoding=encoding, errors=errors)

Parameter Description
object Any object. Specifies the object to convert into a string
encoding The encoding of the object. Default is UTF-8
Specifies what to do if the decoding fails. a response when
errors
decoding fails (can be strict, ignore, replace, etc)

Example
str(object, encoding=’utf-8?, errors=’strict’)

II BCA, IV sem Python Programming


28
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Example 1:
# string representation of Divya
print(str('Divya'))
Output: Divya

Example 2:
x = str(3.5)
print(x)
Output: 3.5

Example 3:
# string representation of Luke
name = str('Luke')
print(name)
# string representation of an integer 40
age = str(40)
print(age)
# string representation of a numeric string 7ft
height = str('7ft')
print(height)
Output
Luke
40
7ft
In the above example, we have used the str() method with different
types of arguments like string, integer, and numeric string.

II BCA, IV sem Python Programming


29
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Note:
Errors in String
There are six types of error taken by this function.
 strict (default): it raises a UnicodeDecodeError.
 ignore: It ignores the unencodable Unicode
 replace: It replaces the unencodable Unicode with a question mark
 xmlcharrefreplace: It inserts XML character reference instead of
the unencodable Unicode
 backslashreplace: inserts a \uNNNN Espace sequence instead of
unencodable Unicode
 namereplace: inserts a \N{…} escape sequence instead of an
unencodable Unicode

Operations on Strings
1. Compare Two Strings
We use the equals == operator to compare two strings. If two strings
are equal, the operator returns True. Otherwise, it returns False.

For example
str1 = "Hello, world!"
str2 = "I love Python."
str3 = "Hello, world!"
# compare str1 and str2
print(str1 == str2)
# compare str1 and str3
print(str1 == str3)
Output
False
True

In the above example,


 str1 and str2 are not equal. Hence, the result is False.
 str1 and str3 are equal. Hence, the result is True.

II BCA, IV sem Python Programming


30
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

2. Join Two or More Strings


In Python, we can join (concatenate) two or more strings using the “+“
operator.

Example
greet = "Hello, "
name = "Jack"
# using + operator
result = greet + name
print(result)

Output: Hello, Jack


In the above example, we have used the “+” operator to join two
strings: greet and name.

3.String Length
In Python, we use the len() method to find the length of a string.
Example
greet = 'Hello'
# count length of greet string
print(len(greet))

Output: 5

II BCA, IV sem Python Programming


31
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Methods of Python String


Besides those mentioned above, there are various string methods
present in Python.
Here are some of those methods:

Methods Description

upper() converts the string to uppercase

lower() converts the string to lowercase

partition() returns a tuple

replace() replaces substring inside

find() returns the index of first occurrence of substring

rstrip() removes trailing characters

split() splits string from left

startswith() checks if string starts with the specified string

isnumeric() checks numeric characters

index() returns index of substring

4. Reversing a Python String


With Accessing Characters from a string, we can also reverse them. We
can Reverse a string by writing [::-1] and the string will be reversed.
Example
#Program to reverse a string
gfg = "Divyasetty"
print(gfg[::-1])

Output:
yttesayvid

II BCA, IV sem Python Programming


32
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

We can also reverse a string by using built-in join and reversed function.

Example
# Program to reverse a string
gfg = "geeksforgeeks"
# Reverse the string using reversed and join function
gfg = "".join(reversed(gfg))
print(gfg)

Output:
skeegrofskeeg

5. String Comparison
The relational operators compare the Unicode values of the characters of
the strings from the 0th index till the end of the string. It then returns a
boolean value according to the operator used.

Example
print("Geek" == "Geek")
print("Geek" < "geek")
print("Geek" > "geek")
print("Geek" != "Geek")

output
True
True
False
False

II BCA, IV sem Python Programming


33
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

6. Slicing and Joining


When working with strings in Python, you may have to split a string into
substrings. Or you might need to join together smaller chunks to form a
string.
Python's split() and join() string methods help you do these tasks
easily.

Join()
The join function is a more flexible way for concatenating string. With join
function, you can add any character into the string.
If you want to add a colon (:) after every character in the string “Python”
you can use the following code.

Example
print(":".join("Python"))

Output
P:y:t:h:o:n

Split()
Split strings is another function that can be applied in Python.
First here we will split the string by using the command ”word.split”
and get the result.

word="AES College GBD"


print(word.split(' '))

Output
['AES', 'College', 'GBD']

II BCA, IV sem Python Programming


34
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

7. Traversing
Traversing a string means accessing all the elements of the string
one after the other by using the subscript. A string can be traversed
using for loop or while loop.

Example
For while loop
In Python, a while loop may have an optional else block.
Here, the else part is executed after the condition of the loop evaluates to
False.
Example
counter = 0
while counter < 3:
print('Inside loop')
counter = counter + 1
else:
print('Inside else')

Output
Inside loop
Inside loop
Inside loop
Inside else

For loop
The for loop is usually used when the number of iterations is known

Example
# this loop is iterated 4 times (0 to 3)
for i in range(4):
print(i)

II BCA, IV sem Python Programming


35
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Output:
0
1
2
3

Format Specifiers
The format() method formats the specified value(s) and insert them
inside the string's placeholder.
The placeholder is defined using curly brackets: {}.The format() method
returns the formatted string.

Syntax

string.format(value1, value2...)

Parameter Values

Parameter Description

Required. One or more values that should be formatted and


inserted in the string.

value1, value2... The values are either a list of values separated by commas,
a key=value list, or a combination of both.

The values can be of any data type.

Example 1
txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))

output
For only 49.00 dollars!

II BCA, IV sem Python Programming


36
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Example 2
#named indexes:

txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)

#numbered indexes:

txt2 = "My name is {0}, I'm {1}".format("John",36)

#empty placeholders:

txt3 = "My name is {}, I'm {}".format("John",36)

print(txt1)

print(txt2)

print(txt3)

Output:

My name is John, I'm 36


My name is John, I'm 36
My name is John, I'm 36

Escape Sequences

Definition: an escape sequence is a sequence of characters with special


meaning when used inside a string or a character.

Syntax: The characters need to be preceded by a backslash character

Example:

print('Interview \n Bit')

Output:

Interview

Bit

II BCA, IV sem Python Programming


37
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Escape character Use


Prints a single quote inside a string enclosed with
\'
single quotes.
Prints a double quote inside a string enclosed with
\"
double-quotes.
Prints the succeeding part of \n even if in the
\n
same line, in a new line
\t Gives a tab space equivalent to 8 normal spaces.
Brings the cursor to the starting of the line, called
\r
as 'carriage return.'
\b Gives a backspace.
Creates an f-string which is a whole new string
\f
formatting mechanism
\ooo Gives the octal representation
\\ Prints a backslash character
\xhh Gives the hexadecimal representation

Raw and Unicode Strings


Raw String
 Raw string literals in Python define normal strings that are prefixed
with either an r or R before the opening quote.
 If a backslash (\) is in the string, the raw string treats this
character as a literal character but not an escape character.

For example,
print(r'\n')
print(r'\t')

Output:
\n
\t

II BCA, IV sem Python Programming


38
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Unicode Strings
Unicode is a standard encoding system that is used to represent
characters from almost all languages. Every Unicode character is encoded
using a unique integer code point between 0 and 0x10FFFF. A Unicode
string is a sequence of zero or more code points.

Example
import sys

# checking the default encoding of string

print "The default encoding for python2 is:",


sys.getdefaultencoding()

output:
The default encoding for python2 is: ascii

String Methods

Function
Description
Name

Converts the first character of the string to a capital (uppercase)


capitalize()
letter

casefold() Implements caseless string matching

center() Pad the string with the specified character.

count() Returns the number of occurrences of a substring in the string.

encode() Encodes strings with the specified encoded scheme

endswith() Returns “True” if a string ends with the given suffix

Specifies the amount of space to be substituted with the “\t” symbol


expandtabs()
in the string

find() Returns the lowest index of the substring if it is found

II BCA, IV sem Python Programming


39
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Function
Description
Name

format() Formats the string for printing it to console

format_map() Formats specified values in a string using a dictionary

index() Returns the position of the first occurrence of a substring in a string

Checks whether all the characters in a given string is alphanumeric


isalnum()
or not

isalpha() Returns “True” if all characters in the string are alphabets

isdecimal() Returns true if all characters in a string are decimal

isdigit() Returns “True” if all characters in the string are digits

isidentifier() Check whether a string is a valid identifier or not

islower() Checks if all characters in the string are lowercase

isnumeric() Returns “True” if all characters in the string are numeric characters

Returns “True” if all characters in the string are printable or the


isprintable()
string is empty

Returns “True” if all characters in the string are whitespace


isspace()
characters

istitle() Returns “True” if the string is a title cased string

isupper() Checks if all characters in the string are uppercase

join() Returns a concatenated String

ljust() Left aligns the string according to the width specified

lower() Converts all uppercase characters in a string into lowercase

lstrip() Returns the string with leading characters removed

maketrans() Returns a translation table

partition() Splits the string at the first occurrence of the separator

replace() Replaces all occurrences of a substring with another substring

rfind() Returns the highest index of the substring

II BCA, IV sem Python Programming


40
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

Function
Description
Name

rindex() Returns the highest index of the substring inside the string

rjust() Right aligns the string according to the width specified

rpartition() Split the given string into three parts

rsplit() Split the string from the right by the specified separator

rstrip() Removes trailing characters

splitlines() Split the lines at line boundaries

startswith() Returns “True” if a string starts with the given prefix

strip() Returns the string with both leading and trailing characters

swapcase() Converts all uppercase characters to lowercase and vice versa

title() Convert string to title case

translate() Modify string according to given translation mappings

upper() Converts all lowercase characters in a string into uppercase

Returns a copy of the string with ‘0’ characters padded to the left
zfill()
side of the string

Example
# Python3 program to show the
# working of upper() function
text = 'geeKs For geEkS'

# upper() function to convert


# string to upper case
print("\nConverted String:")
print(text.upper())

II BCA, IV sem Python Programming


41
Divya S R, Assistant Professor, AESNC, Gauribidanur. Unit-2

# lower() function to convert


# string to lower case
print("\nConverted String:")
print(text.lower())

# converts the first character to


# upper case and rest to lower case
print("\nConverted String:")
print(text.title())

# original string never changes


print("\nOriginal String")
print(text)

Output:

Converted String:
GEEKS FOR GEEKS

Converted String:
geeks for geeks

Converted String:
Geeks For Geeks

Original String
geeKs For geEkS

II BCA, IV sem Python Programming


42

You might also like