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

Final Python Lab Manual

The document contains a series of Python exercises covering various programming concepts such as functions, loops, conditionals, and data manipulation. It includes code snippets for tasks like calculating sums, checking for palindromes, and generating Fibonacci sequences. Each exercise demonstrates practical applications of Python programming techniques.

Uploaded by

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

Final Python Lab Manual

The document contains a series of Python exercises covering various programming concepts such as functions, loops, conditionals, and data manipulation. It includes code snippets for tasks like calculating sums, checking for palindromes, and generating Fibonacci sequences. Each exercise demonstrates practical applications of Python programming techniques.

Uploaded by

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

LabExercise 1

#Calculate the multiplication and sum of two numbers

def multiplication_or_sum(num1, num2):

product = num1 * num2

if product <= 1000:


return product
else:

return num1 + num2

result = multiplication_or_sum(20, 30)


print("The result is", result)

The result is 600

# Print the Sum of a Current Number and a Previous number

print("Printing current and previous number and their sum in a


range(10)")
previous_num = 0

# loop from 1 to 10
for i in range(1, 11):
x_sum = previous_num + i
print("Current Number", i, "Previous Number ", previous_num, "
Sum: ", x_sum)

previous_num = i

Printing current and previous number and their sum in a range(10)


Current Number 1 Previous Number 0 Sum: 1
Current Number 2 Previous Number 1 Sum: 3
Current Number 3 Previous Number 2 Sum: 5
Current Number 4 Previous Number 3 Sum: 7
Current Number 5 Previous Number 4 Sum: 9
Current Number 6 Previous Number 5 Sum: 11
Current Number 7 Previous Number 6 Sum: 13
Current Number 8 Previous Number 7 Sum: 15
Current Number 9 Previous Number 8 Sum: 17
Current Number 10 Previous Number 9 Sum: 19

#Print characters present at an even index number

word = input('Enter word ')


print("Original String:", word)
size = len(word)

print("Printing only even index chars")


for i in range(0, size - 1, 2):
print("index[", i, "]", word[i])

Enter word ayush


Original String: ayush
Printing only even index chars
index[ 0 ] a
index[ 2 ] u

#Remove first n characters from a string

def remove_chars(word, n):


print('Original string:', word)
x = word[n:]
return x

print("Removing characters from a string")


print(remove_chars("pynative", 4))
print(remove_chars("pynative", 2))

Removing characters from a string


Original string: pynative
tive
Original string: pynative
native

#Check if the first and last numbers of a list are the same

def first_last_same(numberList):
print("Given list:", numberList)

first_num = numberList[0]
last_num = numberList[-1]

if first_num == last_num:
return True
else:
return False

numbers_x = [10, 20, 30, 40, 10]


print("result is", first_last_same(numbers_x))

numbers_y = [75, 65, 35, 75, 30]


print("result is", first_last_same(numbers_y))

Given list: [10, 20, 30, 40, 10]


result is True
Given list: [75, 65, 35, 75, 30]
result is False

#Display numbers divisible by 5

num_list = [10, 20, 33, 46, 55]


print("Given list:", num_list)
print('Divisible by 5:')
for num in num_list:
if num % 5 == 0:
print(num)

Given list: [10, 20, 33, 46, 55]


Divisible by 5:
10
20
55

# Find the number of occurrences of a substring in a string


str_x = "Emma is good developer. Emma is a writer"
# use count method of a str class
cnt = str_x.count("Emma")
print(cnt)

#Check Palindrome Number

def palindrome(number):
print("original number", number)
original_num = number

# reverse the given number


reverse_num = 0
while number > 0:
reminder = number % 10
reverse_num = (reverse_num * 10) + reminder
number = number // 10

# check numbers
if original_num == reverse_num:
print("Given number palindrome")
else:
print("Given number is not palindrome")

palindrome(121)
palindrome(125)

original number 121


Given number palindrome
original number 125
Given number is not palindrome

# Merge two lists using the following condition


def merge_list(list1, list2):
result_list = []

for num in list1:

if num % 2 != 0:

result_list.append(num)

for num in list2:

if num % 2 == 0:

result_list.append(num)
return result_list

list1 = [10, 20, 25, 30, 35]


list2 = [40, 45, 60, 75, 90]
print("result list:", merge_list(list1, list2))

result list: [25, 35, 40, 60, 90]

#Get an int value of base raises to the power of exponent

def exponent(base, exp):


num = exp
result = 1
while num > 0:
result = result * base
num = num - 1
print(base, "raises to the power of", exp, "is: ", result)

exponent(5, 4)

5 raises to the power of 4 is: 625


LabExercise 2

# Accept numbers from a user

num1 = int(input("Enter first number "))


num2 = int(input("Enter second number "))

res = num1 * num2


print("Multiplication is", res)

Enter first number 23


Enter second number 21
Multiplication is 483

# Display three string “Name”, “Is”, “James” as “Name**Is**James”

print('My', 'Name', 'Is', 'James', sep='**')

My**Name**Is**James

#Convert Decimal number to octal using print() output formatting


num = 8
print('%o' % num)

10

#Display float number with 2 decimal places using print()

num = 458.541315
print('%.2f' % num)

458.54

#Accept a list of 5 float numbers as an input from the user

numbers = []

for i in range(0, 5):


print("Enter number at location", i, ":")

item = float(input())

numbers.append(item)

print("User List:", numbers)

Enter number at location 0 :


1.2
Enter number at location 1 :
2.1
Enter number at location 2 :
3.2
Enter number at location 3 :
4.2
Enter number at location 4 :
5.3
User List: [1.2, 2.1, 3.2, 4.2, 5.3]

# Accept any three string from one input() call


str1, str2, str3 = input("Enter three string").split()
print('Name1:', str1)
print('Name2:', str2)
print('Name3:', str3)

Enter three stringayush aditya anamika


Name1: ayush
Name2: aditya
Name3: anamika

# Format variables using a string.format() method.

quantity = 3
totalMoney = 1000
price = 450
statement1 = "I have {1} dollars so I can buy {0} football for {2:.2f}
dollars."
print(statement1.format(quantity, totalMoney, price))

I have 1000 dollars so I can buy 3 football for 450.00 dollars.


# Print first 10 natural numbers using while loop

i = 1
while i <= 10:
print(i)
i += 1

1
2
3
4
5
6
7
8
9
10

# Calculate sum of all numbers from 1 to a given number

s = 0
n = int(input("Enter number "))

for i in range(1, n + 1, 1):

s += i
print("\n")
print("Sum is: ", s)

Enter number 6

Sum is: 21

# Print multiplication table of a given number

n = 2

for i in range(1, 11, 1):

product = n * i
print(product)

2
4
6
8
10
12
14
16
18
20

# Display numbers from a list using a loop

numbers = [12, 75, 150, 180, 145, 525, 50]

for item in numbers:


if item > 500:
break
elif item > 150:
continue

elif item % 5 == 0:
print(item)

75
150
145

# Count the total number of digits in a number

num = 75869
count = 0
while num != 0:

num = num // 10

count = count + 1
print("Total digits are:", count)

Total digits are: 5

# Print list in reverse order using a loop

list1 = [10, 20, 30, 40, 50]

new_list = reversed(list1)

for item in new_list:


print(item)

50
40
30
20
10

# Display numbers from -10 to -1 using for loop


for num in range(-10, 0, 1):
print(num)

-10
-9
-8
-7
-6
-5
-4
-3
-2
-1

# Display a message “Done” after the successful execution of the for


loop

for i in range(5):
print(i)
else:
print("Done!")

0
1
2
3
4
Done!

# Print all prime numbers within a range

start = 25
end = 50
print("Prime numbers between", start, "and", end, "are:")

for num in range(start, end + 1):

if num > 1:
for i in range(2, num):

if (num % i) == 0:

break
else:
print(num)

Prime numbers between 25 and 50 are:


29
31
37
41
43
47

# Display Fibonacci series up to 10 terms

num1, num2 = 0, 1

print("Fibonacci sequence:")

for i in range(10):

print(num1, end=" ")

res = num1 + num2

num1 = num2
num2 = res

Fibonacci sequence:
0 1 1 2 3 5 8 13 21 34

# Find the factorial of a given number

num = 5
factorial = 1
if num < 0:
print("Factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:

for i in range(1, num + 1):

factorial = factorial * i
print("The factorial of", num, "is", factorial)

The factorial of 5 is 120

# Reverse a integer number

num = 76542
reverse_number = 0
print("Given Number ", num)
while num > 0:
reminder = num % 10
reverse_number = (reverse_number * 10) + reminder
num = num // 10
print("Revere Number ", reverse_number)
Given Number 76542
Revere Number 24567

# Print elements from a given list present at odd index positions

my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
for i in my_list[1::2]:
print(i, end=" ")

20 40 60 80 100

# Calculate the cube of all numbers from 1 to a given number

input_number = 6
for i in range(1, input_number + 1):
print("Current Number is :", i, " and the cube is", (i * i * i))

Current Number is : 1 and the cube is 1


Current Number is : 2 and the cube is 8
Current Number is : 3 and the cube is 27
Current Number is : 4 and the cube is 64
Current Number is : 5 and the cube is 125
Current Number is : 6 and the cube is 216

# Find the sum of the series up to n terms

n = 5

start = 2
sum_seq = 0

for i in range(0, n):


print(start, end="+")
sum_seq += start

start = start * 10 + 2
print("\nSum of above series is:", sum_seq)

2+22+222+2222+22222+
Sum of above series is: 24690
# Exercise 1: Create a function in Python
# Write a program to create a function that takes two arguments, name
and age, and print their value.

def Name(name, age):


# print value
print(name, age)

Name("Ayush", 20)

Ayush 20

# Exercise 2: Create a function with variable length of arguments


# Write a program to create function func1() to accept a variable
length of arguments and print their value.

def func1(*args):
for i in args:
print(i)

func1(20, 40, 60)


func1(80, 100)

20
40
60
80
100

# Exercise 3: Return multiple values from a function

# Write a program to create function calculation() such that it can


accept two variables
# and calculate addition and subtraction.
# Also, it must return both addition and subtraction in a single
return call.

def calculation(a, b):


addition = a + b
subtraction = a - b

return addition, subtraction


res = calculation(40, 10)
print(res)

(50, 30)

# Exercise 4: Create a function with a default argument


# Write a program to create a function show_employee() using the
following conditions.

# It should accept the employee’s name and salary and display both.
# If the salary is missing in the function call then assign default
value 9000 to salary

def show_employee(name, salary=9000):


print("Name:", name, "salary:", salary)

show_employee("Ayush", 12000)
show_employee("Raj")

Name: Ayush salary: 12000


Name: Raj salary: 9000

# Exercise 5: Create an inner function to calculate the addition in


the following way

# Create an outer function that will accept two parameters, a and b


# Create an inner function inside an outer function that will
calculate the addition of a and b
# At last, an outer function will add 5 into addition and return it

def outer_fun(a, b):


square = a ** 2

def addition(a, b):


return a + b

add = addition(a, b)

return add + 5

result = outer_fun(5, 10)


print(result)

20
# Exercise 6: Create a recursive function
# Write a program to create a recursive function to calculate the sum
of numbers from 0 to 10.

# A recursive function is a function that calls itself again and again

def addition(num):
if num:

return num + addition(num - 1)


else:
return 0

res = addition(10)
print(res)

55

# Exercise 7: Assign a different name to function and call it through


the new name
# Below is the function display_student(name, age). Assign a new name
show_tudent(name, age) to it
# and call it using the new name.

def display_student(name, age):


print(name, age)

display_student("Ayush", 20)

# assign new name


showStudent = display_student
# call using new name
showStudent("Raj", 20)

Ayush 20
Raj 20

# Exercise 8: Generate a Python list of all the even numbers between 4


to 30

print(list(range(4, 30, 2)))

[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]

# Exercise 9: Find the largest item from a given list


x = [4, 6, 8, 24, 12, 2]
print(max(x))

24
lists

March 8, 2025

[1]: # Exercise 1: Reverse a list in Python

list1 = [100, 200, 300, 400, 500]


list1 = list1[::-1]
print(list1)

[500, 400, 300, 200, 100]

[2]: # Exercise 2: Concatenate two lists index-wise

list1 = ["M", "na", "i", "AYUS"]


list2 = ["y", "me", "s", "H"]
list3 = [i + j for i, j in zip(list1, list2)]
print(list3)

['My', 'name', 'is', 'AYUSH']

[4]: # Exercise 3: Turn every item of a list into its square

numbers = [1, 2, 3, 4, 5, 6, 7]
# result list
res = []
for i in numbers:

res.append(i * i)
print(res)

[1, 4, 9, 16, 25, 36, 49]

[5]: # Exercise 4: Concatenate two lists in the following order

list1 = ["Hello ", "take "]


list2 = ["Dear", "Sir"]

res = [x + y for x in list1 for y in list2]


print(res)

['Hello Dear', 'Hello Sir', 'take Dear', 'take Sir']

1
[6]: # Exercise 5: Iterate both lists simultaneously

list1 = [10, 20, 30, 40]


list2 = [100, 200, 300, 400]

for x, y in zip(list1, list2[::-1]):


print(x, y)

10 400
20 300
30 200
40 100

[7]: # Exercise 6: Remove empty strings from the list of strings

list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]

# remove None from list1 and convert result into list


res = list(filter(None, list1))
print(res)

['Mike', 'Emma', 'Kelly', 'Brad']

[9]: # Exercise 7: Add new item to list after a specified item

list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]

list1[2][2].append(7000)
print(list1)

[10, 20, [300, 400, [5000, 6000, 7000], 500], 30, 40]

[10]: # Exercise 8: Extend nested list by adding the sublist

list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
sub_list = ["h", "i", "j"]

list1[2][1][2].extend(sub_list)
print(list1)

['a', 'b', ['c', ['d', 'e', ['f', 'g', 'h', 'i', 'j'], 'k'], 'l'], 'm', 'n']

[12]: # EXERCISE 9 --> REPLACE ITS ITEMS FROM THE NEW VALUE IF FOUND

2
list1 = [5, 10, 15, 20, 25, 50, 20]

# get the first occurrence index


index = list1.index(20)

# update item present at location


list1[index] = 200
print(list1)

[5, 10, 15, 200, 25, 50, 20]

[13]: # Exercise 10: Remove all occurrences of a specific item from a list.

list1 = [5, 20, 15, 20, 25, 50, 20]

def remove_value(sample_list, val):


return [i for i in sample_list if i != val]

res = remove_value(list1, 20)


print(res)

[5, 15, 25, 50]

[ ]:

3
# Exercise 1: Convert two lists into a dictionary

keys = ['Ten', 'Twenty', 'Thirty']


values = [10, 20, 30]

res_dict = dict(zip(keys, values))


print(res_dict)

{'Ten': 10, 'Twenty': 20, 'Thirty': 30}

# Exercise 2: Merge two Python dictionaries into one

dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}


dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}

dict3 = {**dict1, **dict2}


print(dict3)

{'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40, 'Fifty': 50}

# Exercise 3: Print the value of key ‘history’ from the below dict

sampleDict = {
"class": {
"student": {
"name": "Mike",
"marks": {
"physics": 70,
"history": 80
}
}
}
}

print(sampleDict['class']['student']['marks']['history'])

80

# Exercise 4: Initialize dictionary with default values

employees = ['Kelly', 'Emma']


defaults = {"designation": 'Developer', "salary": 8000}

res = dict.fromkeys(employees, defaults)


print(res)

# Individual data
print(res["Kelly"])
{'Kelly': {'designation': 'Developer', 'salary': 8000}, 'Emma':
{'designation': 'Developer', 'salary': 8000}}
{'designation': 'Developer', 'salary': 8000}

# Exercise 5: Create a dictionary by extracting the keys from a given


dictionary

sampleDict = {
"name": "Kelly",
"age":25,
"salary": 8000,
"city": "New york" }

keys = ["name", "salary"]

newDict = {k: sampleDict[k] for k in keys}


print(newDict)

{'name': 'Kelly', 'salary': 8000}

# Exercise 6: Delete a list of keys from a dictionary

sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
"city": "New york"
}
# Keys to remove
keys = ["name", "salary"]

sample_dict = {k: sample_dict[k] for k in sample_dict.keys() - keys}


print(sample_dict)

{'city': 'New york', 'age': 25}

# Exercise 7: Check if a value exists in a dictionary

sample_dict = {'a': 100, 'b': 200, 'c': 300}


if 200 in sample_dict.values():
print('200 present in a dict')

200 present in a dict

# Exercise 8: Rename key of a dictionary

sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
"city": "New york"
}

sample_dict['location'] = sample_dict.pop('city')
print(sample_dict)

{'name': 'Kelly', 'age': 25, 'salary': 8000, 'location': 'New york'}

# Exercise 9: Get the key of a minimum value from the following


dictionary

sample_dict = {
'Physics': 82,
'Math': 65,
'history': 75
}
print(min(sample_dict, key=sample_dict.get))

Math

# Exercise 10: Change value of a key in a nested dictionary

sample_dict = {
'emp1': {'name': 'Jhon', 'salary': 7500},
'emp2': {'name': 'Emma', 'salary': 8000},
'emp3': {'name': 'Brad', 'salary': 6500}
}

sample_dict['emp3']['salary'] = 8500
print(sample_dict)

{'emp1': {'name': 'Jhon', 'salary': 7500}, 'emp2': {'name': 'Emma',


'salary': 8000}, 'emp3': {'name': 'Brad', 'salary': 8500}}
# Exercise 1: Add a list of elements to a set

sample_set = {"Yellow", "Orange", "Black"}


sample_list = ["Blue", "Green", "Red"]

sample_set.update(sample_list)
print(sample_set)

{'Blue', 'Black', 'Red', 'Green', 'Orange', 'Yellow'}

# Exercise 2: Return a new set of identical items from two sets


set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}

print(set1.intersection(set2))

{40, 50, 30}

# Exercise 3: Get Only unique items from two sets

set1 = {10, 20, 30, 40, 50}


set2 = {30, 40, 50, 60, 70}

print(set1.union(set2))

{70, 40, 10, 50, 20, 60, 30}

# Exercise 4: Update the first set with items that don’t exist in the
second set
set1 = {10, 20, 30}
set2 = {20, 40, 50}

set1.difference_update(set2)
print(set1)

{10, 30}

# Exercise 5: Remove items from the set at once

set1 = {10, 20, 30, 40, 50}


set1.difference_update({10, 20, 30})
print(set1)

{50, 40}

# Exercise 6: Return a set of elements present in Set A or B, but not


both
set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}

print(set1.symmetric_difference(set2))
{20, 70, 10, 60}

# Exercise 7: Check if two sets have any elements in common. If yes,


display the common elements

set1 = {10, 20, 30, 40, 50}


set2 = {60, 70, 80, 90, 10}

if set1.isdisjoint(set2):
print("Two sets have no items in common")
else:
print("Two sets have items in common")
print(set1.intersection(set2))

Two sets have items in common


{10}

# Exercise 8: Update set1 by adding items from set2, except common


items
set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}

set1.symmetric_difference_update(set2)
print(set1)

{20, 70, 10, 60}

# Exercise 9: Remove items from set1 that are not common to both set1
and set2

set1 = {10, 20, 30, 40, 50}


set2 = {30, 40, 50, 60, 70}

set1.intersection_update(set2)
print(set1)
# Exercise 1: Reverse the tuple

tuple1 = (10, 20, 30, 40, 50)


tuple1 = tuple1[::-1]
print(tuple1)

(50, 40, 30, 20, 10)

# Exercise 2: Access value 20 from the tuple

tuple1 = ("Orange", [10, 20, 30], (5, 15, 25))

print(tuple1[1][1])

20

# Exercise 3: Create a tuple with single item 50

tuple1= (50, )
print(tuple1)

(50,)

# Exercise 4: Unpack the tuple into 4 variables


tuple1 = (10, 20, 30, 40)

a, b, c, d = tuple1
print(a)
print(b)
print(c)
print(d)

10
20
30
40

# Exercise 5: Swap two tuples in Python

tuple1 = (11, 22)


tuple2 = (99, 88)
tuple1, tuple2 = tuple2, tuple1
print(tuple2)
print(tuple1)

(11, 22)
(99, 88)

# Exercise 6: Copy specific elements from one tuple to a new tuple


tuple1 = (11, 22, 33, 44, 55, 66)
tuple2 = tuple1[3:-1]
print(tuple2)
(44, 55)

# Exercise 7: Modify the tuple

tuple1 = (11, [22, 33], 44, 55)


tuple1[1][0] = 222
print(tuple1)

(11, [222, 33], 44, 55)

# Exercise 8: Sort a tuple of tuples by 2nd item


tuple1 = (('a', 23), ('b', 37), ('c', 11), ('d', 29))
tuple1 = tuple(sorted(list(tuple1), key=lambda x: x[1]))
print(tuple1)

(('c', 11), ('a', 23), ('d', 29), ('b', 37))

# Exercise 9: Counts the number of occurrences of item 50 from a tuple


tuple1 = (50, 10, 60, 70, 50)
print(tuple1.count(50))

# Exercise 10: Check if all items in the tuple are the same

def check(t):
return all(i == t[0] for i in t)

tuple1 = (45, 45, 45, 45)


print(check(tuple1))

True
# Exercise 1
# Create a string made of the first, middle and last character

str1 = 'Ayush'
print("Given string is: ", str1)

first_character = str1[0]

length_of_the_string = len(str1)

middle_index_of_the_string = int(length_of_the_string / 2)

first_character = first_character + str1[middle_index_of_the_string]

first_character = first_character + str1[length_of_the_string - 1]

print("String with first middle and the last character is: ",
first_character)

Given string is: Ayush


String with first middle and the last character is: Auh

# Exercise 2: Append new string in the middle of a given string

# Given two strings, s1 and s2. Write a program to create a new string
s3 by appending s2 in the middle of s1.

s1 = "Ault"
s2 = "Kelly"

lenght_of_the_string_s1 = len(s1)

middle_index_of_the_s1 = int(lenght_of_the_string_s1/2)

get_char_from_zero_to_middle = x = s1[:middle_index_of_the_s1:]

get_char_from_zero_to_middle = get_char_from_zero_to_middle + s2

get_char_from_zero_to_middle = get_char_from_zero_to_middle +
s1[middle_index_of_the_s1:]

print(get_char_from_zero_to_middle)
AuKellylt

# Exercise 3: Create a new string made of the first, middle, and last
characters of each input string

# Given two strings, s1 and s2, write a program to return a new string
made
# of s1 and s2’s first, middle, and last characters.

s1 = "America"
s2 = "Japan"

first_char = s1[0] + s2[0]

middle_char = s1[int(len(s1) / 2):int(len(s1) / 2) + 1] +


s2[int(len(s2) / 2):int(len(s2) / 2) + 1]

last_char = s1[len(s1) - 1] + s2[len(s2) - 1]


res = first_char + middle_char + last_char
print("Mix String is ", res)

Mix String is AJrpan

# Exercise 4: Arrange string characters such that lowercase letters


should come first

# # Given string contains a combination of the lower and upper case


letters.
# Write a program to arrange the characters of a string so that all
lowercase letters should come first.

str1 = "PyNaTive"

lower = []
upper = []

for char in str1:


if char.islower():

lower.append(char)
else:
upper.append(char)
sorted_str = ''.join(lower + upper)
print('Result:', sorted_str)

Result: yaivePNT

# Exercise 5: Count all letters, digits, and special symbols from a


given string

str1 = "P@#yn26at^&i5ve"

char_count = 0
digit_count = 0
symbol_count = 0

for char in str1:

if char.isalpha():

char_count += 1
elif char.isdigit():
digit_count += 1

else:
symbol_count += 1

print("Chars =", char_count, "Digits =", digit_count, "Symbol =",


symbol_count)

Chars = 8 Digits = 3 Symbol = 4

# Exercise 6: Create a mixed String using the following rules

# Given two strings, s1 and s2. Write a program to create a new string
s3 made of the first char of s1,
# then the last char of s2, Next, the second char of s1 and second
last char of s2, and so on.
# Any leftover chars go at the end of the result.

s1 = "Abc"
s2 = "Xyz"

s1_length = len(s1)
s2_length = len(s2)

length = s1_length if s1_length > s2_length else s2_length


result = ""

s2 = s2[::-1]
for i in range(length):
if i < s1_length:
result = result + s1[i]
if i < s2_length:
result = result + s2[i]

print(result)

AzbycX

# Exercise 7: String characters balance Test

# Write a program to check if two strings are balanced. For example,


strings s1 and s2 are balanced
# if all the characters in the s1 are present in s2. The character’s
position doesn’t matter.

def string_balance_test(s1, s2):


flag = True
for char in s1:
if char in s2:
continue
else:
flag = False
return flag

s1 = "Yn"
s2 = "PYnative"
flag = string_balance_test(s1, s2)
print("s1 and s2 are balanced:", flag)

s1 and s2 are balanced: True

# Exercise 8: Find all occurrences of a substring in a given string by


ignoring the case

# Write a program to find all occurrences of “USA” in a given string


ignoring the case.

str1 = "Welcome to USA. usa awesome, isn't it?"


sub_string = "USA"

temp_str = str1.lower()
# use count function
count = temp_str.count(sub_string.lower())
print("The USA count is:", count)

The USA count is: 2

# Exercise 9: Calculate the sum and average of the digits present in a


string

# Given a string s1, write a program to return the sum and average of
the digits that appear in the string,
# ignoring all other characters.

input_str = "PYnative29@#8496"
total = 0
cnt = 0
for char in input_str:
if char.isdigit():
total += int(char)
cnt += 1

avg = total / cnt


print("Sum is:", total, "Average is ", avg)

Sum is: 38 Average is 6.333333333333333

# Exercise 10: Write a program to count occurrences of all characters


within a string

str1 = "Apple"

char_dict = dict()

for char in str1:


count = str1.count(char)

char_dict[char] = count
print('Result:', char_dict)

Result: {'A': 1, 'p': 2, 'l': 1, 'e': 1}

# Exercise 11: Reverse a given string

str1 = "PYnative"
print("Original String is:", str1)

str1 = str1[::-1]
print("Reversed String is:", str1)

Original String is: PYnative


Reversed String is: evitanYP
# Exercise 12: Find the last position of a given substring

# Write a program to find the last position of a substring “Emma” in a


given string.

str1 = "Emma is a data scientist who knows Python. Emma works at


google."
print("Original String is:", str1)

index = str1.rfind("Emma")
print("Last occurrence of Emma starts at index:", index)

Original String is: Emma is a data scientist who knows Python. Emma
works at google.
Last occurrence of Emma starts at index: 43

# Exercise 13 Split a string on hyphens

# Write a program to split a given string on hyphens and display each


substring.

str1 = "Emma-is-a-data-scientist"
print("Original String is:", str1)

# split string
sub_strings = str1.split("-")

print("Displaying each substring")


for sub in sub_strings:
print(sub)

Original String is: Emma-is-a-data-scientist


Displaying each substring
Emma
is
a
data
scientist

# Exercise 14: Remove empty strings from a list of strings

str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]


res_list = []
for s in str_list:

if s:
res_list.append(s)
print(res_list)

['Emma', 'Jon', 'Kelly', 'Eric']


# Exercise 15: Remove special symbols / punctuation from a string

import string

str1 = "/*Jon is @developer & musician"


print("Original string is ", str1)

new_str = str1.translate(str.maketrans('', '', string.punctuation))

print("New string is ->> ", new_str)

Original string is /*Jon is @developer & musician


New string is ->> Jon is developer musician

# Exercise 16: Removal all characters from a string except integers

str1 = 'I am 25 years and 10 months old'


print("Original string is", str1)

res = "".join([item for item in str1 if item.isdigit()])

print(res)

Original string is I am 25 years and 10 months old


2510

# Exercise 17: Find words with both alphabets and numbers

str1 = "Emma25 is Data scientist50 and AI Expert"


print("The original string is : " + str1)

res = []

temp = str1.split()

for item in temp:


if any(char.isalpha() for char in item) and any(char.isdigit() for
char in item):
res.append(item)

print("Displaying words with alphabets and numbers")


for i in res:
print(i)

The original string is : Emma25 is Data scientist50 and AI Expert


Displaying words with alphabets and numbers
Emma25
scientist50

# Exercise 18: Replace each special symbol with # in the following


string
import string

str1 = '/*Jon is @developer & musician!!'


print("The original string is : ", str1)

replace_char = '#'

for char in string.punctuation:


str1 = str1.replace(char, replace_char)

print("The strings after replacement : ", str1)

The original string is : /*Jon is @developer & musician!!


The strings after replacement : ##Jon is #developer # musician##
jw1o9b0dn

March 8, 2025

[2]: # The basic validation


# A simple Python regex to validate string against email format and catch the␣
↪most obvious syntax errors:

# this is the pattern r"^\S+@\S+\.\S+$"

# --------> Python code

import re

email_validate_pattern = r"^\S+@\S+\.\S+$"

re.match(email_validate_pattern, "[email protected]")

extract_email_pattern = r"\S+@\S+\.\S+"

re.findall(extract_email_pattern, 'You can reach me out at [email protected]


↪and [email protected]')

[2]: ['[email protected]', '[email protected]']

[3]: # ZIP code regex


# A regular expression to test a string against ZIP code format:

# ---> this is the pattern "^[0-9]{5}(?:-[0-9]{4})?$"

# ---------> python code

import re

# Validate ZIP code

1
words_pattern = "^[0-9]{5}(?:-[0-9]{4})?$"
re.match(words_pattern, '80001')
re.match(words_pattern, '80001-2222')
re.match(words_pattern, '800010')

# Extract ZIP code from a string


words_extract_pattern = "[0-9]{5}(?:-[0-9]{4})?"
re.findall(words_extract_pattern, 'My zip code is 80001')

[3]: ['80001']

[5]: # Extract value between XML tags


# One of the most common operations with XML and regex is the extraction of the
# text between certain tags (a.k.a. scraping). For this operation, the␣
↪following regular expression can be used.

# ------------> this is the pattern "(?:<from.*?>)(.*?)(?:<\\/from>)"

# Extract text between specific XML tag


xml_pattern = "(?:<from.*?>)(.*?)(?:<\\/from>)"
re.findall(xml_pattern, '<note><to>Tove</to><from>Ayush</
↪from><heading>Reminder</heading><body>Don\'t forget me this weekend!</body></

↪note>')

[5]: ['Ayush']

[6]: # The basic international phone number validation


# A simple regex to validate string against a valid international phone number␣
↪format without delimiters and

# with an optional plus sign:

# ---------> this is the pattern "^\\+?[1-9][0-9]{7,14}$"

import re

validate_phone_number_pattern = "^\\+?[1-9][0-9]{7,14}$"
re.match(validate_phone_number_pattern, "+12223334444") # Returns Match object

# Extract phone number from a string


extract_phone_number_pattern = "\\+?[1-9][0-9]{7,14}"

2
re.findall(extract_phone_number_pattern, 'You can reach me out at +12223334444␣
↪and +56667778888')

[6]: ['+12223334444', '+56667778888']

[9]: # Strong password regex

# --------> this is the pattern "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?


↪[#?!@$%^&*-]).{8,}$"

import re

# Validate strong password


password_pattern = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).
↪{8,}$"

re.match(password_pattern, 'Ayush') # Returns None


re.match(password_pattern, '-Secr3t.') # Returns Match object

[9]: <re.Match object; span=(0, 8), match='-Secr3t.'>

[10]: # Basic numbers only regex


# Below is a simple regular expression that allows validating if a given string␣
↪contains only numbers:

# ----------> this is the pattern "^\\d+$"

import re

# Validate number
number_pattern = "^\\d+$"
re.match(number_pattern, '42') # Returns Match object
re.match(number_pattern, 'notanumber') # Returns None

# Extract number from a string


number_extract_pattern = "\\d+"
re.findall(number_extract_pattern, 'Your message was viewed 203 times.') #␣
↪returns ['203']

[10]: ['203']

[12]: # Simple word match

3
# The regular expression to match only words looks like this (including␣
↪compound words):

# ------------> this is the pattern "^\\b(?:\\w|-)+\\b$"

# Validate words
words_pattern = "^\\b(?:\\w|-)+\\b$"
re.match(words_pattern, 'word') # Returns Match object
re.match(words_pattern, 'pet-friendly') # Returns Match object
re.match(words_pattern, 'not a word') # Returns None

# Extract words from a string


words_extract_pattern = "\\b(?:\\w|-)+\\b"
re.findall(words_extract_pattern, 'Hello, world!') # returns ['Hello', 'world',␣
↪'a boy']

[12]: ['Hello', 'world']

[14]: # Simple Mac address regex (IEEE 802)


# Below is a simple mac address regex that supports dashes or colons as␣
↪separators:

# ----------------> this is the pattern "^(?:[0-9A-Fa-f]{2}[:-]){5}(?:


↪[0-9A-Fa-f]{2})$"

import re

# Validate Mac address


mac_address_validate_pattern = "^(?:[0-9A-Fa-f]{2}[:-]){5}(?:[0-9A-Fa-f]{2})$"
re.match(mac_address_validate_pattern, "00:00:5e:00:53:af") # Returns Match␣
↪object

# Extract mac address from a string


extract_mac_address_pattern = "(?:[0-9A-Fa-f]{2}[:-]){5}(?:[0-9A-Fa-f]{2})"
re.findall(extract_mac_address_pattern, 'Unknown error in node 00:00:5e:00:53:
↪af. Terminating.')

[14]: ['00:00:5e:00:53:af']

[16]: # Match all HTML tags


# Below is a simple regex to validate the string against HTML tag pattern.
# This can be later used to remove all tags and leave text only.

4
# -----> this is the pattern "<(?:\"[^\"]*\"['\"]*|'[^']*'['\"]*|[^'\">])+>"

html_pattern = "<(?:\"[^\"]*\"['\"]*|'[^']*'['\"]*|[^'\">])+>"
re.sub(html_pattern, '', '<html><body>Hello, <b>world</b>!<br /></body></html>')

[16]: 'Hello, world!'

[17]: # Simple date regex (DD/MM/YYYY)


# Below is a simple regex to validate the string against a date format (D/M/
↪YYYY or M/D/YYYY).

# This however does not guarantee that the date would be valid. You can also␣
↪replace \\/ with a separator you need.

# -------> this is the pattern "^[0-9]{1,2}\\/[0-9]{1,2}\\/[0-9]{4}$"

import re

# Validate date
date_pattern = "^[0-9]{1,2}\\/[0-9]{1,2}\\/[0-9]{4}$"
re.match(date_pattern, '12/12/2022') # Returns Match object

# Extract date from a string


date_extract_pattern = "[0-9]{1,2}\\/[0-9]{1,2}\\/[0-9]{4}"
re.findall(date_extract_pattern, 'I\'m on vacation from 1/18/2021 till 1/29/
↪2021')

[17]: ['1/18/2021', '1/29/2021']

[ ]:

5
untitled10

March 8, 2025

[4]: # import RE module


import re

target_str = "My roll number is 25"


res = re.findall(r"\d", target_str)
# extract mathing value
print(res)

['2', '5']

[7]: # import the RE module


import re

target_string = "Jessa salary is 8000$"

# compile regex pattern


# pattern to match any character
str_pattern = r"\w"
pattern = re.compile(str_pattern)

# match regex pattern at start of the string


res = pattern.match(target_string)
# match character
print(res.group())
# Output 'J'

# search regex pattern anywhere inside string


# pattern to search any digit
res = re.search(r"\d", target_string)
print(res.group())
# Output 8

# pattern to find all digits


res = re.findall(r"\d", target_string)
print(res)
# Output ['8', '0', '0', '0']

# regex to split string on whitespaces

1
res = re.split(r"\s", target_string)
print("All tokens:", res)
# Output ['Jessa', 'salary', 'is', '8000$']

# regex for replacement


# replace space with hyphen
res = re.sub(r"\s", "-", target_string)
# string after replacement:
print(res)
# Output Jessa-salary-is-8000$

J
8
['8', '0', '0', '0']
All tokens: ['Jessa', 'salary', 'is', '8000$']
Jessa-salary-is-8000$

[8]: import re

# Target String one


str1 = "Emma's luck numbers are 251 761 231 451"

# pattern to find three consecutive digits


string_pattern = r"\d{3}"
# compile string pattern to re.Pattern object
regex_pattern = re.compile(string_pattern)

# print the type of compiled pattern


print(type(regex_pattern))
# Output <class 're.Pattern'>

# find all the matches in string one


result = regex_pattern.findall(str1)
print(result)
# Output ['251', '761', '231', '451']

# Target String two


str2 = "Kelly's luck numbers are 111 212 415"
# find all the matches in second string by reusing the same pattern
result = regex_pattern.findall(str2)
print(result)
# Output ['111', '212', '415']

<class 're.Pattern'>
['251', '761', '231', '451']
['111', '212', '415']

2
[9]: import re

target_string = "Emma is a basketball player who was born on June 17"


result = re.match(r"\w{4}", target_string) #

# printing the Match object


print("Match object: ", result)
# Output re.Match object; span=(0, 4), match='Emma'

# Extract match value


print("Match value: ", result.group())
# Output 'Emma'

Match object: <re.Match object; span=(0, 4), match='Emma'>


Match value: Emma

[10]: import re

# Target String
target_string = "Emma is a baseball player who was born on June 17"

# search() for eight-letter word


result = re.search(r"\w{8}", target_string)

# Print match object


print("Match Object", result)
# output re.Match object; span=(10, 18), match='baseball'

# print the matching word using group() method


print("Matching word: ", result.group())
# Output 'baseball'

Match Object <re.Match object; span=(10, 18), match='baseball'>


Matching word: baseball

[11]: import re

target_string = "Emma is a basketball player who was born on June 17, 1993. She␣
↪played 112 matches with scoring average 26.12 points per game. Her weight is␣

↪51 kg."

result = re.findall(r"\d+", target_string)

# print all matches


print("Found following matches")
print(result)

# Output ['17', '1993', '112', '26', '12', '51']

3
Found following matches
['17', '1993', '112', '26', '12', '51']

[12]: import re

target_string = "My name is maximums and my luck numbers are 12 45 78"


# split on white-space
word_list = re.split(r"\s+", target_string)
print(word_list)

# Output ['My', 'name', 'is', 'maximums', 'and', 'my', 'luck', 'numbers',␣


↪'are', '12', '45', '78']

['My', 'name', 'is', 'maximums', 'and', 'my', 'luck', 'numbers', 'are', '12',
'45', '78']

[13]: import re

target_str = "Jessa knows testing and machine learning"


res_str = re.sub(r"\s", "_", target_str)
# String after replacement
print(res_str)
# Output 'Jessa_knows_testing_and_machine_learning'

Jessa_knows_testing_and_machine_learning

[14]: import re

target_string = "The price of PINEAPPLE ice cream is 20"

# two groups enclosed in separate ( and ) bracket


result = re.search(r"(\b[A-Z]+\b).+(\b\d+)", target_string)

# Extract matching values of all groups


print(result.groups())
# Output ('PINEAPPLE', '20')

# Extract match value of group 1


print(result.group(1))
# Output 'PINEAPPLE'

# Extract match value of group 2


print(result.group(2))
# Output 20

('PINEAPPLE', '20')
PINEAPPLE
20

4
[15]: import re

target_string = "Emma loves \n Python"


# dot(.) metacharacter to match any character
result = re.search(r'.', target_string)
print(result.group())
# Output 'E'

# .+ to match any string except newline


result = re.search(r'.+', target_string)
print(result.group())
# Output 'Emma loves '

E
Emma loves

[16]: import re

target_str = "Jessa is a Python developer, and her salary is 8000"

# \A to match at the start of a string


# match word starts with capital letter
result = re.findall(r"\A([A-Z].*?)\s", target_str)
print("Matching value", result)
# Output ['Jessa']

# \Z to match at the end of a string


# match number at the end of the string
result = re.findall(r"\d.*?\Z", target_str)
print("Matching value", result)
# Output ['8000']

Matching value ['Jessa']


Matching value ['8000']

[17]: import re

target_str = "KELLy is a Python developer at a PYnative. kelly loves ML and AI"

# Without using re.I


result = re.findall(r"kelly", target_str)
print(result)
# Output ['kelly']

# with re.I
result = re.findall(r"kelly", target_str, re.I)
print(result)

5
# Output ['KELLy', 'kelly']

# with re.IGNORECASE
result = re.findall(r"kelly", target_str, re.IGNORECASE)
print(result)
# Output ['KELLy', 'kelly']

['kelly']
['KELLy', 'kelly']
['KELLy', 'kelly']

[ ]:

You might also like