Problem Solving and Python Programming
1
Strings: string slices, immutability, string functions and methods, string module
Problem Solving and Python Programming
2
Strings
Problem Solving and Python Programming
3
a="hello world"
a=‘hello world’
Strings Concatenation
Problem Solving and Python Programming
4
Example:
a=“Hai”
b=“how are you” c=a+b
print(c)
Operators on String
Problem Solving and Python Programming
5
>>> print("Python"*10) PythonPythonPythonPythonPythonPython PythonPythonPythonPython
Operations on String
String Slicing
Problem Solving and Python Programming
7
String Slicing
Problem Solving and Python Programming
8
Python slicing can be done in two ways:
String Slicing
Problem Solving and Python Programming
9
Using the slice() method�
Problem Solving and Python Programming
10
Syntax:
Parameters:
start: Starting index where the slicing of object starts.
stop: Ending index where the slicing of object stops.
step: It is an optional argument that determines the increment between each index for slicing.
# String slicing
String = 'ASTRING'
# Using slice constructor
s1 = slice(3)
s2 = slice(1, 5, 2)
s3 = slice(-1, -12, -2)
print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])
Output:
String slicing
AST
SR
GITA
String Slicing
Problem Solving and Python Programming
12
A start, end, and step have the same mechanism as the slice() constructor.
string_variablename [ start:end]
Syntax
arr[start:stop] # items start through stop-1
arr[start:] # items start through the rest of the array
arr[:stop] # items from the beginning through stop-1
arr[:] # a copy of the whole array
arr[start:stop:step] # start through not past stop, by step
String Slice example
Problem Solving and Python Programming
14
s=“hello”
H | e | l | l | o |
0 | 1 | 2 | 3 | 4 |
-5 | -4 | -3 | -2 | -1 |
Example:
String = 'GEEKSFORGEEKS’
print(String[1:5:2]) # EK
Strings are immutable
Problem Solving and Python Programming
16
Strings are immutable
1) %s method
2)format( )
3)f-string method
String formatting using %s
Problem Solving and Python Programming
18
print("My name is %s and i secured %d marks in python” % ("Arbaz",92))
My name is Arbaz and i secured 92 marks in python
print(“My name is %s and my age is %d and my percentage is %f" %("Amar",22,99.65))
Output:
My name is Amar and my age is 22 and my percentage is 99.65
format( ) method
The format() method formats the specified value(s) and insert them inside the string's placeholder.
Syntax:
string.format(value1, value2...)
txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
�txt2 = "My name is {0}, I'm {1}” .format("John",36)
�txt3 = "My name is {}, I'm {}” .format("John",36)
myorder = "I have a {carname}, it is a {model}.”
�print(myorder.format(carname = "Ford", model = “Figo"))
f-string( ) method
print(f “I Love {a}”)
www.w3schools.com/python/ref_string_format.asp
String Comparision
Problem Solving and Python Programming
25
Example of string comparision
Problem Solving and Python Programming
26
str1="green" str2="black"
print("Is both Equal:", str1==str2) print("Is str1> str2:", str1>str2) print("Is str1< str2:", str1<str2)
OUTPUT:
Is both Equal: False Is str1> str2: True Is str1< str2: False
String functions and methods
Problem Solving and Python Programming
27
len() | min() | max() | isalnum() | isalpha() |
isdigit() | islower() | isuppe() | isspace() | isidentifier() |
endswith() | startswith() | find() | count() | capitalize() |
title() | lower() | upper() | swapcase() | replace() |
center() | ljust() | rjust() | center() | isstrip() |
rstrip() | strip() | | | |
Inbuilt String functions
Problem Solving and Python Programming
28
What is ASCII values
Problem Solving and Python Programming
29
Example for Inbuilt string functions
Problem Solving and Python Programming
30
name=input("Enter Your name:") print("Welcome",name)
print("Length of your name:",len(name)) print("Maximum value of chararacter in your name", max(name))
print("Minimum value of character in your name",min(name))
OUTPUT
Problem Solving and Python Programming
31
Enter Your name: PRABHAKAR Welcome PRABHAKAR
Length of your name: 9
Maximum value of chararacter in your name R Minimum value of character in your name A
i) Converting string functions
Problem Solving and Python Programming
32
captitalize() | Only First character capitalized |
lower() | All character converted to lowercase |
upper() | All character converted to uppercase |
title() | First character capitalized in each word |
swapcase() | Lower case letters are converted to Uppercase and Uppercase letters are converted to Lowercase |
replace(old,new) | Replaces old string with new string |
Program:
str=input("Enter any string:") print("String Capitalized:", str.capitalize()) print("String lower case:", str.lower()) print("String upper case:", str.upper()) print("String title case:", str.title()) print("String swap case:", str.swapcase())
print("String replace case:",str.replace("python","python programming"))
Problem Solving and Python Programming 18
Output:
Enter any string: Welcome to python String Capitalized: Welcome to python String lower case: welcome to python String upper case: WELCOME TO PYTHON String title case: Welcome To Python String swap case: wELCOME TO PYTHON
String replace case: Welcome to python programming
ii)Formatting String functions
Problem Solving and Python Programming
34
center(width) | Returns a string centered in a field of given width |
ljust(width) | Returns a string left justified in a field of given width |
rjust(width) | Returns a string right justified in a field of given width |
format(items) | Formats a string |
Program:
a=input("Enter any string:") print("Center alignment:", a.center(20)) print("Left alignment:", a.ljust(20)) print("Right alignment:", a.rjust(20))
Problem Solving and Python Programming
35
Output:
iii) Removing whitespace characters function
Problem Solving and Python Programming
36
lstrip() | Returns a string with leading whitespace characters removed |
rstrip() | Returns a string with trailing whitespace characters removed |
strip() | Returns a string with leading and trailing whitespace characters removed |
Program
Problem Solving and Python Programming
37
a=input("Enter any string:") print("Left space trim:",a.lstrip()) print("Right space trim:",a.rstrip()) print("Left and right trim:",a.strip())
Output:
iv) Testing String/Character function
Problem Solving and Python Programming 23
isalnum() | Returns true if all characters in string are alphanumeric and there is at least one character |
isalpha() | Returns true if all characters in string are alphabetic |
isdigit() | Returns true if string contains only number character |
islower() | Returns true if all characters in string are lowercase letters |
isupper() | Returns true if all characters in string are uppercase letters |
isspace() | Returns true if string contains only whitespace characters. |
Program
Problem Solving and Python Programming
39
a=input("Enter any string:") print("Alphanumeric:",a.isalnum()) print("Alphabetic:",a.isalpha()) print("Digits:",a.isdigit()) print("Lowecase:",a.islower())
print("Upper:",a.isupper())
Output:
v) Searching for substring
Problem Solving and Python Programming
40
Endswith() | Returns true if the strings ends with the substring |
Startswith() | Returns true if the strings starts with the substring |
Find() | Returns the lowest index or -1 if substring not found |
Count() | Returns the number of occurrences of substring |
Program
Problem Solving and Python Programming
41
a=input("Enter any string:")
print("Is string ends with thon:", a.endswith("thon")) print("Is string starts with good:", a.startswith("good")) print("Find:", a.find("ython"))
print("Count:", a.count(“o"))
Output:
Enter any string : welcome to python
Is string ends with thon: True
Is string starts with good: False
Find: 12
Count: 3
String Methods
Problem Solving and Python Programming
42
Mostly used string methods are:�
upper()
lower()
split()
join()
replace()
find()
count()
Example
text = "Monty Python Flying Circus"
# Perform various string operations directly on the string
print("Upper:", text.upper()) # Convert the string to uppercase
print("Lower:", text.lower()) # Convert the string to lowercase
print("Split:", text.split()) # Split the string into a list of words
# Join the words in the list using '+' as the separator
print("Join:", "+".join(text.split()))
# Replace occurrences of "Python" with "Java" in the string
print("Replace:", text.replace("Python", "Java"))
# Find the index of the substring "Python" in the string
print("Find:", text.find("Python"))
# Count the number of occurrences of the letter "n" in the string
print("Count:", text.count("n"))
Output
Problem Solving and Python Programming
45
Upper: “MONTY PYTHON FLYING CIRCUS”
Lower: “monty python flying circus”
Split: ["Monty", "Python", "Flying", "Circus"]
Join : Monty+Python+Flying+Circus Replace: Monty Java Flying Circus
Find: 7
Count: 3
Sample programs
1. Write a program to check given character is uppercase or lower case
2. Write a program to find a specific word in a given string and replace it with another word
3. Write a program to count the number of occurrence of specific character in a given string
4. Write a program to display the string in the following format
Hi*Everyone* I *Love*Pyton
Method -1 without constructor
# empty list my_list = [ ]
# list of integers
my_list = [1, 2, 3]
# list with mixed datatypes my_list = [1, "Hello", 3.4]
# nested list
my_list = [“welcome", [8, 4, 6]]
Method-2 using list constructor
# empty list my_list = list()
# list of integers
my_list = list([1, 2, 3])
Example: marks=[90,80,50,70,60]
print(marks[0])
Output: 90
Nested list:
my_list = [“welcome", [8, 4, 6]]
print(marks[1][0])
Output: 8
my_list = ['p','r','o','b','e']
print(my_list[-1])
#Output: e
print(my_list[-5])
# Output: p
#Change Elements
>>> marks=[90,60,80]
>>> print(marks) [90, 60, 80]
>>> marks[1]=100
>>> print(marks) [90, 100, 80]
#Add Elements
>>> marks.append(50)
>>> print(marks) [90, 100, 80, 50]
>>> marks.extend([60,80,70])
>>> print(marks) [90, 100, 80, 50, 60, 80, 70]
>>> marks.insert(3,40)
>>> print(marks) [90, 100, 80, 40, 50, 60, 80, 70]
>>> print(marks)
[90, 100, 80, 40, 50, 60, 80, 70]
>>> del marks[6]
>>> print(marks) [90, 100, 80, 40, 50, 60, 70]
>>> del marks
>>> print(marks)
Output: NameError: name 'marks' is not defined.
>>> marks.clear()
>>> print(marks) # output [ ]
Difference b/w del and clear( )
del:
The del keyword in python deletes the objects.
clear():
clear() erases the elements in the dictionary.
>>> marks=[90,60,80]
>>> marks.remove(80)
>>> print(marks) [90, 60]
>>> marks.remove(100)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module> marks.remove(100)
ValueError: list.remove(x): x not in list
>>> marks=[100,20,30]
>>> marks.pop() #30 is deleted
>>> print(marks) [100, 20]
>>> >>> marks.pop(0) #100 is deleted
>>> print(marks) [20]
number_list = []
n = int(input("Enter the list size "))
for i in range(0, n):
print("Enter number at index", i,)
item = int(input())
number_list.append(item)
print("User list is ", number_list)
Output:
Enter the list size 5
Enter number at index 0
55
Enter number at index 1
33
Enter number at index 2
77
Enter number at index 3
88
Enter number at index 4
1
User list is [55, 33, 77, 88, 1]
Program to receive the list elements and display
number_list = []
n = int(input("Enter the list size "))
for i in range(0, n):
print("Enter number at index", i, )
item = int(input())
number_list.append(item)
print("User list is ", number_list)
print("Sum = ", sum(number_list))
Output:
Enter the list size 4
Enter number at index 0
22
Enter number at index 1
11
Enter number at index 2
4
Enter number at index 3
6
User list is [22, 11, 4, 6]
Sum = 43
Program to receive the list elements and find the sum
Shallow copy of a list using copy() method
list=[10,20,30]
new_list=list.copy()
print(list) # [10, 20,30]
print( new_list) #[10, 20,30]
list.append(50)
print( list) #[10, 20,30, 50]
print( new_list) #[10, 20,30]
3
tup=(10,20,30,40)
tup[2]=50
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
tup[2]=50
TypeError: 'tuple' object does not support item assignment
Creating a Tuple from user Input in Python�
Examples:
my_tuple = tuple(input('Enter space-separated words: ').split())
print(my_tuple)
Output:
Enter space-separated words: 3 5 2 7 1
('3', '5', '2', '7', '1')
Creating a Tuple from user Input in Python�
Examples:
user_input = input('Enter space-separated integers: ')
my_tuple = tuple(int(item) for item in user_input.split())
print(my_tuple)
Output:
Enter space-separated integers: 3 4 6 7
(3, 4, 6, 7)
Creating a Tuple from user Input in Python�
user_input = input('Enter space-separated integers: ')
my_tuple = tuple(int(item) for item in user_input.split())
print(my_tuple)
c=my_tuple[0]+my_tuple[1]
print(“Result=“,c)
Output:
Enter space-separated integers: 3 4 6 7
(3, 4, 6, 7)
Result=7
Similar to List,
Method | Description |
Return the number of items that is equal to x | |
Return index of first item that is equal to x |
Function | Description |
Return True if all elements of the tuple are true (or if the tuple is empty). | |
Return True if any element of the tuple is true. If the tuple is empty, return False. | |
Return an enumerate object. It contains the index and value of all the items of tuple as pairs. | |
Return the length (the number of items) in the tuple. | |
Return the largest item in the tuple. | |
Return the smallest item in the tuple | |
Take elements in the tuple and return a new sorted list (does not sort the tuple itself). | |
Retrun the sum of all elements in the tuple. | |
Convert an iterable (list, string, set, dictionary) to a tuple. |
Try all the built-in functions with example.
Example
Converting list to tuple and tuple to list
tup=(10,20,30)
print(list(tup)) # [10, 20, 30]
print(tuple(tup)) #(10, 20, 30)
user_input = input('Enter space-separated integers: ')
my_tuple = tuple(int(item) for item in user_input.split())
print(my_tuple)
print(max(my_tuple))
print(min(my_tuple))
def summation(test_tup):
# Initializing count
count = 0
for i in test_tup:
count += i
return count
# Initializing test_tup
test_tup = (5, 20, 3, 7, 6, 8)
print(summation(test_tup))
tuple_ = (5, 2, 24, 3, 1, 6, 7)
sorted_ = tuple(sorted(tuple_))
print('Sorted Tuple :', sorted_)
print(type(sorted_))
OR
tuple_ = ('Itika', 'Arshia', 'Peter', 'Parker')
list(tuple_).sort()
print(tuple_)
print(type(tuple_))
set={1,1,2,2,3}
print(set)
Output:
{1, 2, 3}
The values True and 1 are considered the same value in sets, and are treated as duplicates:
Example:
set={"apple", "banana", "cherry", True, 1, 2}��print(set)
Output:
{True, 2, 'banana', 'cherry', 'apple'}
A set can contain elements of different type
A set cannot contain lists.
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
Get the Length of a Set using len()
Method | Operator | |
union | | | |
intersection | & | |
difference | - | |
symmetric_difference | ^ | |
Create 3 lists namely TCS, Infosys, Wipro with some set of students in each list. Convert the lists to set. Now print the students placed in any of these companies with count.
3
3
3
# Get index of 'germany': ind_ger
# Use ind_ger to print out capital of Germany
Output:
Maths
Science
Social
Output:
maths : 45
science : 23
social : 55
Method | Description |
Remove all items form the dictionary. | |
Return a shallow copy of the dictionary. | |
Return a new dictionary with keys from seq and value equal to v(defaults to None). | |
Return the value of key. If key doesnot exit, return d (defaults to None). | |
Return a new view of the dictionary's items (key, value). | |
Return a new view of the dictionary's keys. | |
Remove the item with key and return its value or d if key is not found. If d is not provided and key is not found, raises KeyError. | |
Remove and return an arbitary item (key, value). Raises KeyError if the dictionary is empty. | |
If key is in the dictionary, return its value. If not, insert key with a value of d and return d (defaults to None). | |
Update the dictionary with the key/value pairs from other, overwriting existing keys. | |
Return a new view of the dictionary's values |
Function | Description |
Return the length (the number of items) in the dictionary. | |
Return a new sorted list of keys in the dictionary. |
countryCapitals[‘india’] = ‘delhi’
Files
fhand= open(“filename”, “mode”)
Opening files
OR
fhand = open('c:/users/roopa/desktop/sample.txt')
fhand = open(‘sample.txt’)
Print(fhand)
Mode | Meaning |
r | Opens a file for reading purpose. If the specified file does not exist in the specified path, or if you don‟t have permission, error message will be displayed. This is the default mode of open() function in Python. |
w | Opens a file for writing purpose. If the file does not exist, then a new file with the given name will be created and opened for writing. If the file already exists, then its content will be over-written. |
A | Opens a file for appending the data. If the file exists, the new content will be appended at the end of existing content. If no such file exists, it will be created and new content will be written into it. |
r+ | Opens a file for reading and writing. |
w+ | Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. |
a+ | Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading |
Rb | Opens a file for reading only in binary format |
Wb | Opens a file for writing only in binary format |
Ab | Opens a file for appending only in binary format |
Reading files�
sample.txt |
Python is a high level programming language it is introduced by Guido van rossam. Python is easy to learn and simple to code an application |
Print_count.py |
fhand = open('sample.txt’) count = 0 for line in fhand: count = count + 1 print('Line :', count, line) print('LineCount:', count) fhand.close() |
Output: |
Line : 1 Python is a high level programming language Line : 2 it is introduced by Guido van rossam. Line : 3 Python is easy to learn and simple to code an application
Line Count: 3 |
2. The second way of reading a text file loads the entire file into a string :�
You can read the whole file into one string using the read method on the file handle.
Letting the user choose the file name�
fname =input('Enter the file name: ‘)
fhand = open(fname)
Writing files
write a file, you have to open it with mode “w” as a second parameter:
fout = open('output.txt', 'w’)
print(fout)
<_io.TextIOWrapper name='output.txt’
mode='w' encoding='cp1252’>
out the old data and starts fresh, If the file doesn’t exist, a
new one is created.
line1 = “Hello,How are you\n"
fout.write(line1)
Closing a file:
fout.close( )
Append mode
When the file is opened in append mode, the handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
# Append-adds at last
file1 = open("myfile.txt", "a") # append mode
file1.write("Today \n")
file1.close()
PYTHON-INHERITANCE
What is Inheritance
Inheritance is the ability to ‘inherit’ features or attributes from already
attributes are defined data structures and the functions we
written classes into newer classes we make. These features and
can
perform with them, a.k.a. Methods. It promotes code reusability, which is considered one of the best industrial coding practices as it makes the codebase modular.
In python inheritance, new class/es inherits from older class/es. The new class/es copies all the older class's functions and attributes without rewriting the syntax in the new class/es. These new classes are called derived classes, and old ones are called base classes.
Types of Inheritance in Python
Parent1 -> Child1 : Single Inheritance
Parent1 -> Child1 -> Child2 : Multi – Level Inheritance Parent1 -> Child2 <- Parent2 : Multiple Inheritance
Single Inheritance in python
Single Inheritance is the simplest form of inheritance where a single child class is derived from a single parent class. Due to its candid nature, it is also known as Simple Inheritance.
Single Inheritance Example
Multiple Inheritance in Python
In multiple inheritance, a single child class is inherited from two or more parent classes. It means the child class has access to all the parent classes' methods and attributes.
Multiple Inheritance Example
Multilevel Inheritance in Python
In multilevel inheritance, we go beyond just a parent-child relation. We introduce grandchildren, great-grandchildren, grandparents, etc. We have seen only two levels of inheritance with a superior parent class/es and a derived class/es, but here we can have multiple levels where the parent class/es itself is derived from another class/es.
Example for MultiLevel Inheritance
Hierarchical Inheritance
Hierarchical Inheritance is the right opposite of multiple inheritance. It means that, there are multiple derived child classes from a single parent class.
Example for Hierarchical Inheritance
Hybrid Inheritance in Python
Hybrid Inheritance is the mixture of two or more different types of inheritance. Here we can have many relationships between parent and child classes with multiple levels.
Example for Hybrid Inheritance
Advantage of Inheritance in Python
Increases modularity, i.e., breaking down codebase into modules, making it easier to understand. Here, each class we define becomes a separate module that can be inherited separately by one or many classes.
Code Reusability: the child class copies all the attributes and methods of the parent class into its class and use. It saves time and coding effort by not rewriting them, thus following modularity paradigms.
Modular Codebase:
Less Development and Maintenance Costs:
changes need to be made in the base class; all
derived classes will automatically follow.
Disadvantage of Inheritance in Python
Decreases the Execution Speed: loading multiple classes because they are interdependent
Tightly Coupled Classes: this means that even though parent classes can be executed independently, child classes cannot be executed without defining their parent classes.