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

Unit-Ii-Python Theory Notes

Python programming

Uploaded by

RCW CS 18
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)
43 views

Unit-Ii-Python Theory Notes

Python programming

Uploaded by

RCW CS 18
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

III UNIT-II – PYTHON PROGRAMMING Page No.

:1

PYTHON PROGRAMMING
UNIT-II
Control Flow Statements – If statement – If else statement – If elif else statement – nested if statement - while
loop – for loop – continue and break statements – catching exceptions using try and except statement – syntax
errors – exceptions – exception handling – Strings – str() function - Basic string operations – String
comparison – Built in functions using strings – Accessing characters in string – String slicing – String joining
– split() method – string traversing.
CONTROL FLOW STATEMENTS
The flow control statements are divided into three categories

1. Conditional statements
2. Iterative statements.
3. Transfer statements

Decision-making statements in programming languages decide the direction of the flow of program
execution. In Python, if-else elif statement is used for decision making.

CONDITIONAL STATEMENTS

The decisions are made on the validity of the particular conditions. Condition checking is the backbone of
decision making.

There are three types of conditional statements.

1. if statement
2. if-else
3. if-elif-else
4. nested if-else

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS


III UNIT-II – PYTHON PROGRAMMING Page No.:2

if statement
if statement is the most simple decision-making statement. It is used to decide whether a certain statement
or block of statements will be executed or not i.e if a certain condition is true then a block of statement is
executed otherwise not.
Syntax:

if condition:
# Statements to execute if
# condition is true

Here, the condition after evaluation will be either true or false. if the statement accepts boolean values – if
the value is true then it will execute the block of statements below it otherwise not. We can
use condition with bracket ‘(‘ ‘)’ also.
As we know, python uses indentation to identify a block. So the block under an if statement will be
identified as shown in the below example:

if condition:
statement1
statement2

Here if the condition is true, if block will consider only statement1 to be inside its block.
Flowchart of Python if statement

Example: Python if Statement


# python program to illustrate If statement
i = 10
if (i > 15): Output:
print("10 is less than 15") I am Not in if
print("I am Not in if")

As the condition present in the if statement is false. So, the block below the if statement is executed.

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS


III UNIT-II – PYTHON PROGRAMMING Page No.:3

if-else Statement
The if statement alone tells us that if a condition is true it will execute a block of statements and if the
condition is false it won’t. But what if we want to do something else if the condition is false. Here comes
the else statement. We can use the else statement with if statement to execute a block of code when the
condition is false.

Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

FlowChart of Python if-else statement

Example 1: Python if-else statement


i = 20
if (i < 15): Output:
print("i is smaller than 15")
i is greater than 15
print("i'm in if Block")
else: i'm in else Block
print("i is greater than 15")
print("i'm in else Block") i'm not in if and not in else Block
print("i'm not in if and not in else Block")
The block of code following the else statement is executed as the condition present in the if statement is
false after calling the statement which is not in block(without spaces).

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS


III UNIT-II – PYTHON PROGRAMMING Page No.:4

Example 2: Python if else in list comprehension


def digitSum(n):
dsum = 0
for ele in str(n):
dsum += int(ele) Output
return dsum [16, 3, 18, 18]
List = [367, 111, 562, 945, 6726, 873]
newList = [digitSum(i) for i in List if i & 1]
print(newList)
if-elif-else Ladder
Here, a user can decide among multiple options. The ‘if’ statements are executed from the top down. As
soon as one of the conditions controlling the ‘if’ is true, the statement associated with that if is executed,
and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be
executed.

Syntax:
if (condition):
statement
elif (condition):
statement
.
.
else:
statement

FlowChart of Python if else elif statements

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS


III UNIT-II – PYTHON PROGRAMMING Page No.:5

Example: Python if else elif statements


i = 20
if (i == 10): Output:
print("i is 10")
elif (i == 15): i is 20
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
nested-if
A nested if is an if statement that is the target of another if statement. Nested if statements mean an if
statement inside another if statement. Yes, Python allows us to nest if statements within if statements. i.e,
we can place an if statement inside another if statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here

Flowchart of Python Nested if Statement

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS


III UNIT-II – PYTHON PROGRAMMING Page No.:6

Example: Python Nested if


i = 10
if (i == 10): Output:

if (i < 15): i is smaller than 15


print("i is smaller than 15") i is smaller than 12 too
if (i < 12):
print("i is smaller than 12 too")
else:
print("i is greater than 15")
Iterative statements
In Python, iterative statements allow us to execute a block of code repeatedly as long as the condition is
True. We also call it a loop statements. Python provides us the following two loop statement to perform some
actions repeatedly.
1. for loop
2. while loop
for loop:Using for loop, we can iterate any sequence or iterable variable. The sequence can be
string, list, dictionary, set, or tuple.

Syntax of for loop:


for element in sequence:

body of for loop

Example to display first ten numbers using for loop Output

for i in range(1, 11): 1


2
3
print(i)
4
5
6
7
8
9
10

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS


III UNIT-II – PYTHON PROGRAMMING Page No.:7

While Loop

While Loop is used to execute a block of statements repeatedly until a given condition is satisfied. And
when the condition becomes false, the line immediately after the loop in the program is executed.

Syntax:
while expression:
statement(s)

Flowchart of While Loop:

While loop falls under the category of indefinite iteration. Indefinite iteration means that the number of
times the loop is executed isn’t specified explicitly in advance. Statements represent all the statements
indented by the same number of character spaces after a programming construct are considered to be part
of a single block of code. Python uses indentation as its method of grouping statements. When a while loop
is executed, expr is first evaluated in a Boolean context and if it is true, the loop body is executed. Then the
expr is checked again, if it is still true then the body is executed again and this continues until the expression
becomes false.
Example to calculate the sum of first ten numbers
num = 10
sum = 0
Output
i=1
while i <= num:
sum = sum + i
Sum of first 10 number is: 55
i=i+1
print("Sum of first 10 number is:", sum)
Transfer statements
In Python, transfer statements are used to alter the program’s way of execution in a certain manner. For this
purpose, we use three types of transfer statements.

1. break statement
2. continue statement
3. pass statements
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS
III UNIT-II – PYTHON PROGRAMMING Page No.:8

Break Statement
The break statement is used inside the loop to exit out of the loop. It is useful when we want to terminate
the loop as soon as the condition is fulfilled instead of doing the remaining iterations. It reduces execution
time. Whenever the controller encountered a break statement, it comes out of that loop immediately.

Example of using a break statement Output


for num in range(10): 0
if num > 5: 1
print("stop processing.") 2
break 3
print(num) 4
5
stop processing.
Continue statement
The continue statement is used to skip the current iteration and continue with the next iteration.

Let’s see how to skip a for a loop iteration if the number is 5 and continue executing the body of the loop for
other numbers.

Example of a continue statement


Output
for num in range(3, 8): 3
4
if num == 5:
6
continue
7
else:
print(num)
Pass statement
The pass is the keyword In Python, which won’t do anything. Sometimes there is a situation in programming
where we need to define a syntactically empty block. We can define that block with the pass keyword. A pass
statement is a Python null statement. When the interpreter finds a pass statement in the program, it returns no
operation. Nothing happens when the pass statement is executed. It is useful in a situation where we are
implementing new methods or also in exception handling. It plays a role like a placeholder.
Example

months = ['January', 'June', 'March', 'April'] Output


for mon in months:
['January', 'June', 'March', 'April']
pass
print(months)
EXCEPTION HANDLING
Syntax Error and Exceptions
Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It leads to the
termination of the program. Output:
Example:
amount = 10000
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS


III UNIT-II – PYTHON PROGRAMMING Page No.:9

Exceptions: 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: Output:
marks = 10000
# perform division with 0
a = marks / 0
print(a)

In the above example raised the ZeroDivisionError as we are trying to divide a number by 0.

catching exceptions using try and except statement


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.

a = [1, 2, 3] Output
try:
print ("Second element = %d" %(a[1])) Second element = 2
print ("Fourth element = %d" %(a[3]))
except: An error occurred
print ("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.

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 IndexError in the above code.
The general syntax for adding specific exceptions are-
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
Example: Catching specific exception in Python
def fun(a):
if a < 4: Output
b = a/(a-3) ZeroDivisionError Occurred and Handled
print("Value of b = ", b)
try:
fun(3)
fun(5)
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS
III UNIT-II – PYTHON PROGRAMMING Page No.:10

except NameError:
print("NameError Occurred and Handled")

If you comment on the line fun(3), the output will be NameError Occurred and Handled
The output above is so because as soon as python tries to access the value of b, NameError occurs.
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: Try with else clause
def AbyB(a , b):
try: Output:
c = ((a+b) / (a-b)) -5.0
except ZeroDivisionError:
a/b result in 0
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)

Finally Keyword
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:
try:
k = 5//0 # raises divide by zero exception. Output:
print(k) Can't divide by zero
except ZeroDivisionError:
print("Can't divide by zero") This is always executed
finally:
print('This is always executed')

Raising Exception
The raise statement allows the programmer to force a specific exception to occur. The sole argument in raise
indicates the exception to be raised. This must be either an exception instance or an exception class (a class
that derives from Exception).
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS
III UNIT-II – PYTHON PROGRAMMING Page No.:11

try:
raise NameError("Hi there") # Raise Error
except NameError:
print ("An exception")
raise
The output of the above code will simply line printed as “An exception” but a Runtime error will also
occur in the last due to the raise statement in the last line. So, the output on your command line will look
like
Traceback (most recent call last):
File "/home/d6ec14ca595b97bff8d8034bbf212a9f.py", line 5, in <module>
raise NameError("Hi there") # Raise Error
NameError: Hi there

STRINGS IN PYTHON
A string is a data structure in Python that represents a sequence of characters. It is an immutable data type,
meaning that once you have created a string, you cannot change it. Strings are used widely in many different
applications, such as storing and manipulating text data, representing names, addresses, and other types of
data that can be represented as text.

str( ) function
Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes.
The computer does not understand the characters; internally, it stores manipulated character as the
combination of the 0's and 1's.

Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are also called
the collection of Unicode characters.

In Python, strings can be created by enclosing the character or the sequence of characters in the quotes. Python
allows us to use single quotes, double quotes, or triple quotes to create the string.

Syntax:

str = "Hi Python !"


Here, if we check the type of the variable str using a Python script
print(type(str)), then it will print a string (str).

In Python, strings are treated as the sequence of characters, which means that Python doesn't support the
character data-type; instead, a single character written as 'p' is treated as the string of length 1.

Creating String in Python

We can create a string by enclosing the characters in single-quotes or double- quotes. Python also provides
triple-quotes to represent the string, but it is generally used for multiline string or docstrings.

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS


III UNIT-II – PYTHON PROGRAMMING Page No.:12

#Using single quotes


str1 = 'Hello Python' Output:
print(str1)
Hello Python
#Using double quotes
str2 = "Hello Python" Hello Python
print(str2) Triple quotes are generally used for

represent the multiline or


#Using triple quotes
str3 = '''''Triple quotes are generally used for docstring
represent the multiline or
docstring'''
print(str3)
Strings indexing and splitting
Like other languages, the indexing of the Python strings starts from 0. For example, The string "HELLO" is
indexed as given in the below figure.

Example:
Output:
str = "HELLO" H
E
print(str[0])
L
print(str[1]) L
print(str[2]) O
print(str[3]) IndexError: string index out of range
print(str[4])
# It returns the IndexError because 6th index doesn't exist
print(str[6])

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS


III UNIT-II – PYTHON PROGRAMMING Page No.:13

As shown in Python, the slice operator [] is used to access the individual characters of the string. However,
we can use the : (colon) operator in Python to access the substring from the given string. Consider the
following example.

Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if str = 'HELLO'
is given, then str[1:3] will always include str[1] = 'E', str[2] = 'L' and nothing else.

Consider the following example:

# Given String
Output:
str = "JAVATPOINT"
# Start Oth index to end JAVATPOINT
print(str[0:])
AVAT
# Starts 1th index to 4th index
print(str[1:5]) VA
# Starts 2nd index to 3rd index
JAV
print(str[2:4])
# Starts 0th to 2nd index TPO
print(str[:3])
#Starts 4th to 6th index
print(str[4:7])

We can do the negative slicing in the string; it starts from the rightmost character, which is indicated as -1.
The second rightmost index indicates -2, and so on.

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS


III UNIT-II – PYTHON PROGRAMMING Page No.:14

Consider the following image.

Consider the following example Output:

T
str = 'JAVATPOINT'
I
print(str[-1]) NT
print(str[-3]) OIN
ATPOI
print(str[-2:])
TNIOPTAVAJ
print(str[-4:-1]) IndexError: string index out of range
print(str[-7:-2])
# Reversing the given string
print(str[::-1])
print(str[-12])
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string object doesn't support
item assignment i.e., A string can only be replaced with new string since its content cannot be partially
replaced. Strings are immutable in Python.
Example
str = "HELLO" Output:
str[0] = "h" Traceback (most recent call last):
print(str) File "12.py", line 2, in <module>
str[0] = "h";
TypeError: 'str' object does not support item assignment

However, in example 1, the string str can be assigned completely to a new content as specified in the
following example.
str = "HELLO"
print(str) Output:
str = "hello"
HELLO
print(str)
hello

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS


III UNIT-II – PYTHON PROGRAMMING Page No.:15

Deleting the String

As we know that strings are immutable. We cannot delete or remove the characters from the string. But
we can delete the entire string using the del keyword.

str = "JAVATPOINT" Output:


del str[1]
TypeError: 'str' object doesn't support item deletion
Now we are deleting entire string.

str1 = "JAVATPOINT" Output:


del str1
NameError: name 'str1' is not defined
print(str1)
String Operators
Operator Description

+ It is known as concatenation operator used to join the strings given either side of the
operator.

* It is known as repetition operator. It concatenates the multiple copies of the same string.

[] It is known as slice operator. It is used to access the sub-strings of a particular string.

[:] It is known as range slice operator. It is used to access the characters from the specified
range.

in It is known as membership operator. It returns if a particular sub-string is present in the


specified string.

not in It is also a membership operator and does the exact reverse of in. It returns true if a
particular substring is not present in the specified string.

r/R It is used to specify the raw string. Raw strings are used in the cases where we need to
print the actual meaning of escape characters such as "C://python". To define any string
as a raw string, the character r or R is followed by the string.

% It is used to perform string formatting. It makes use of the format specifiers used in C
programming like %d or %f to map their values in python. We will discuss how
formatting is done in python.

Example

Consider the following example to understand the real use of Python operators.

str = "Hello"

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS


III UNIT-II – PYTHON PROGRAMMING Page No.:16

str1 = " world"


Output:
print(str*3) # prints HelloHelloHello HelloHelloHello
print(str+str1)# prints Hello world Hello world
o
print(str[4]) # prints o
ll
print(str[2:4]); # prints ll False
print('w' in str) # prints false as w is not present in str False
C://python37
print('wo' not in str1) # prints false as wo is present in str1. The string str : Hello
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello
Accessing characters in Python String
In Python, individual characters of a String can be accessed by using the method of Indexing. Indexing
allows negative address references to access characters from the back of the String, e.g. -1 refers to the last
character, -2 refers to the second last character, and so on.
While accessing an index out of the range will cause an IndexError. Only Integers are allowed to be passed
as an index, float or other types that will cause a TypeError.

EXAMPLE:
String1 = "GeeksForGeeks" Output:
print("Initial String: ") Initial String:
print(String1) GeeksForGeeks
First character of String is:
# Printing First character G
print("\nFirst character of String is: ") Last cha racter of String is:
print(String1[0]) s

# Printing Last character


print("\nLast character of String is: ")
print(String1[-1])

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:
gfg = "pythonprogramming"
print(gfg[::-1])
Output:
gnimmargorpnohtyp

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS


III UNIT-II – PYTHON PROGRAMMING Page No.:17

We can also reverse a string by using built-in join and reversed function.
Example
gfg = "pythonprogramming"
gfg = "".join(reversed(gfg))
print(gfg)
Output:
gnimmargorpnohtyp

String Slicing
To access a range of characters in the String, the method of slicing is used. Slicing in a String is done by
using a Slicing operator (colon).
Example
String1 = "GeeksForGeeks"
print("Initial String: ") Output:
print(String1) Initial String:
GeeksForGeeks
# Printing 3rd to 12th character Slicing characters from 3-12:
print("\nSlicing characters from 3-12: ") ksForGeek
print(String1[3:12]) Slicing characters between 3rd and
2nd last character:
# Printing characters between ksForGee
# 3rd and 2nd last character
print("\nSlicing characters between " +
"3rd and 2nd last character: ")
print(String1[3:-2])

String Comparison
To compare Strings in Python.
Method 1: Using Relational Operators
The relational operators compare the Unicode values of the characters of the strings from the zeroth index
till the end of the string. It then returns a boolean value according to the operator used.
Example:
“Geek” == “Geek” will return True as the Unicode of all the
characters are equal
In case of “Geek” and “geek” as the unicode of G is \u0047 and of
g is \u0067
“Geek” < “geek” will return True and
“Geek” > “geek” will return False

print("Geek" == "Geek")
print("Geek" < "geek")
print("Geek" > "geek")
print("Geek" != "Geek")
Output:
True
True
False
False

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS


III UNIT-II – PYTHON PROGRAMMING Page No.:18

Method 2: Using is and is not


The == operator compares the values of both the operands and checks for value equality.
Whereas is operator checks whether both the operands refer to the same object or not. The same is the
case for != and is not.
Let us understand this with an example:
str1 = "Geek" Output:
str2 = "Geek" ID of str1 = 0x7f6037051570
str3 = str1 ID of str2 = 0x7f6037051570
print("ID of str1 =", hex(id(str1))) ID of str3 = 0x7f6037051570
print("ID of str2 =", hex(id(str2))) True
print("ID of str3 =", hex(id(str3))) True
print(str1 is str1) True
print(str1 is str2) ID of changed str1 = 0x7f60356137d8
print(str1 is str3) ID of str4 = 0x7f60356137a0
str1 += "s" False
str4 = "Geeks"
print("\nID of changed str1 =", hex(id(str1)))
print("ID of str4 =", hex(id(str4)))
print(str1 is str4)

The object ID of the strings may vary on different machines. The object IDs of str1, str2 and str3 were
the same therefore they the result is True in all the cases. After the object id of str1 is changed, the
result of str1 and str2 will be false. Even after creating str4 with the same contents as in the new str1,
the answer will be false as their object IDs are different.

Vice-versa will happen with is not.


Method 3: Creating a user-defined function.
By using relational operators we can only compare the strings by their unicodes. In order to compare two
strings according to some other parameters, we can make user-defined functions.
In the following code, our user-defined function will compare the strings based upon the number of digits.
def compare_strings(str1, str2):
count1 = 0
count2 = 0 Output:
for i in range(len(str1)): False
if str1[i] >= "0" and str1[i] <= "9": False
count1 += 1
for i in range(len(str2)): True
if str2[i] >= "0" and str2[i] <= "9":
count2 += 1
return count1 == count2
print(compare_strings("123", "12345"))
print(compare_strings("12345", "geeks"))
print(compare_strings("12geeks", "geeks12"))
Built in functions using strings
Python string is a sequence of Unicode characters that is enclosed in the quotations marks. In this article,
we will discuss the in-built function i.e. the functions provided by the Python to operate on strings.
Case Changing of Strings
The below functions are used to change the case of the strings.
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS
III UNIT-II – PYTHON PROGRAMMING Page No.:19

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


 upper(): Converts all lowercase characters in a string into uppercase
 title(): Convert string to title case
Example: Changing the case of Python Strings. Output:
text = 'geeKs For geEkS' Converted String:
print("\nConverted String:") GEEKS FOR GEEKS
print(text.upper()) Converted String:
print("\nConverted String:") geeks for geeks
print(text.lower()) Converted String:
print("\nConverted String:") Geeks For Geeks
print(text.title()) Original String
print("\nOriginal String") geeKs For geEkS
print(text)

String Methods in Python


Function Name Description

capitalize() Converts the first character of the string to a capital (uppercase) 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

expandtabs() Specifies the amount of space to be substituted with the “\t” symbol in the string

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

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

isalnum() Checks whether all the characters in a given string is alphanumeric or not

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

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS


III UNIT-II – PYTHON PROGRAMMING Page No.:20

Function Name Description

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

isprintable() Returns “True” if all characters in the string are printable or the string is empty

isspace() Returns “True” if all characters in the string are whitespace 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

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

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

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS


III UNIT-II – PYTHON PROGRAMMING Page No.:21

Function Name Description

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

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

String Traversing/Iterate over characters of a string in Python


In Python, while operating with String, one can do multiple operations on it. Let’s see how to iterate over
characters of a string in Python. Example #1: Using simple iteration and range()

string_name = "geeksforgeeks"
Output:
# Iterate over the string geeksforgeeks
for element in string_name:
print(element, end=' ') G
print("\n") E
E
# Code #2 K
string_name = "GEEKS" S
# Iterate over index
for element in range(0, len(string_name)):
print(string_name[element])

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS


III UNIT-II – PYTHON PROGRAMMING Page No.:22

Example #2: Using enumerate() function


Output:
string_name = "Geeks"
G
e
# Iterate over the string
e
for i, v in enumerate(string_name):
k
print(v)
s
Example #3: Iterate characters in reverse order
string_name = "GEEKS" Output:
SKEEG
# slicing the string in reverse fashion s
for element in string_name[ : :-1]: k
print(element, end =' ') e
print('\n') e
g
# Code #2 r
string_name = "geeksforgeeks" o
f
# Getting length of string s
ran = len(string_name) k
e
# using reversed() function e
for element in reversed(range(0, ran)): g
print(string_name[element])
Example #4: Iteration over particular set of element. Perform iteration over string_name by passing
particular string index values.
string_name = "geeksforgeeks"
Output:
# string_name[start:end:step] geeksfor
for element in string_name[0:8:1]:
print(element, end =' ')
Example #5: Iterate characters using itertools
Alternatively, you can use the islice() function from itertools to iterate over the characters of a string.
islice() returns an iterator that returns selected elements from the input iterator, allowing you to specify
the start and end indices of the elements you want to iterate over. Here’s an example of how you can use
islice() to iterate over the characters of a string:
import itertools

string = "hello"

# Create an iterator that returns the characters from index 1 to the end of the string
char_iter = itertools.islice(string, 0, None) Output
h
# Iterate over the selected characters e
for char in char_iter: l
print(char) l
o

------------------------- UNIT-II - COMPLETED -----------------------

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,BOMMAYAPALAYAM-MS.K.RATHI DEVI-DEPT. OF CS

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy