Python - Unit III
Python - Unit III
Strings: string slices, immutability, string functions and methods, string module. Dictionaries:
Operations (create, access, add, remove) and methods. (Insert, delete). Set operation (Access, Add,
Remove). Illustrative programs: creates a dictionary of radius of a circle and its circumference.
1. (i) Define methods in a string with an example program using at least 5 methods. (ii) How to
access characters of a string?
STRING
A string in Python is a sequence of characters enclosed in single quotes (' '), double quotes (" "), or
triple quotes (''' ''' or """ """). Strings are used to store and manipulate text.
# Double quotes
string2 = "Python Programming"
1. Indexing in Strings
• Definition: Accessing individual characters in a string using the subscript ([]) operator.
• Index: A position number assigned to each character in the string.
• Indexing Rules:
o The first character has index 0.
o The last character has index n-1 (where n is the length of the string).
o Negative indexing allows access from the end (-1 for the last character, -2 for second
last, etc.).
o Accessing an index beyond limits raises an error.
2. Traversing a String
• Definition: Accessing characters in a string one by one.
Indexing with while loop
text = "Python"
i = 0
while i < len(text):
print(text[i])
i += 1
Note : Python allows you to access spaces within a string using indexing because spaces are also treated as characters.
1
print(result) # Output: Hello World
STRING METHODS
A string method is a built-in function in Python that allows us to manipulate and process string data
easily. These methods perform various operations such as case conversion, trimming spaces, replacing
substrings, and more.
1. Case Conversion Methods
Method Description Example
upper() Converts all characters to "hello".upper() → "HELLO"
uppercase.
lower() Converts all characters to lowercase. "HELLO".lower() → "hello"
title() Converts the first letter of each "hello world".title() → "Hello
word to uppercase. World"
capitalize() Converts the first letter of the string text = "python programming"
to uppercase. result = text.capitalize()
print(result)
O/p : Python programming
swapcase() Swaps uppercase to lowercase and "Python".swapcase() → "pYTHON"
vice versa.
2
3
(ii) How to access characters of a string?
1. Accessing Characters Using Indexing P
• In Python, strings are like arrays of characters.
h
• Each character has an index starting from 0.
text = "Python"
n
print(text[0]) # First character
print(text[3]) # Fourth character
print(text[-1]) # Last character (negative index)
4
Explanation:
P y t h o n
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
text = "Python"
print(text[0:4]) # From index 0 to 3 ("Pyth")
print(text[:3]) # From start to index 2 ("Pyt")
print(text[2:]) # From index 2 to end ("thon")
print(text[-3:]) # Last 3 characters ("hon")
✓ In Python, strings are immutable, meaning once created, they cannot be changed.
✓ If you try to modify a string, a new string is created instead of modifying the existing one.
✓ Since strings cannot be modified directly, you must create a new string.
Example
str = "Hi"
str[0] = 'B' # Attempt to modify the first character
print(str)
✓ This will raise a TypeError: 'str' object does not support item assignment because modifying
a character directly is not allowed.
➢ Mutable objects are that we can modify according to our requirements and use according to
our use. A few examples of them are List, Dictionary, and Set.
Deleting a String
• You cannot delete characters from a string, but you can delete the entire string using del:
str = "Hello"
del str # This deletes the variable reference, not modifying the string itself
Example Program
# Original string
greeting = "Good Morning" G o o d M o r n i n g
5 0 1 2 3 4 5 6 7 8 9 10 11
# Attempting to change a character (will cause an error)
try:
greeting[5] = 'E' # Trying to replace 'M' with 'E'
except TypeError as e:
print("Error:", e)
Output
# Correct way: Creating a new string
Error: 'str' object does not
new_greeting = greeting[:5] + 'E' + greeting[6:]
support item assignment
Original String: Good Morning
print("Original String:", greeting)
Modified String: Good Eorning
print("Modified String:", new_greeting)
2. String Concatenation:
String concatenation refers to combining multiple strings into one.
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)
6
15. Create a program to determine whether a string is a palindrome or not.
Algorithm
i. Start
ii. Input: Read a string from the user.
iii. Preprocess:
• Convert the string to lowercase to ensure case insensitivity.
• Remove spaces (if necessary) to allow for multi-word palindromes.
iv. Reverse the String:
• Create a reversed version of the string.
v. Compare:
• If the original string (after preprocessing) is the same as its reversed version, it is a
palindrome.
• Otherwise, it is not a palindrome.
vi. Output the result: Print whether the string is a palindrome or not.
vii. End
Program
def is_palindrome(s):
# Remove spaces and convert to lowercase for uniformity
s = s.replace(" ", "").lower()
7. (i) Analyze string slicing. Illustrate how it is done in python with an example.
(ii) Write a python code to search a string in the given list.
(i) Analyze string slicing. Illustrate how it is done in python with an example.
7
Basic Syntax of String Slicing
8
string_list = ["apple", "banana", "cherry", "date", "elderberry"]
Explanation:
1. List of strings is predefined (string_list).
2. User inputs the string to search.
3. The program checks if the string exists in the list using in keyword.
4. If found, it prints "found"; otherwise, it prints "not found".
4. Write a Python program to count the number of vowels in a string provided by the user.
Explanation:
11. Write a function that takes a string as a parameter and replaces the first letter of every word
with the corresponding uppercase letter.
Explanation:
✓ string.title() converts the first letter of every word in the string to uppercase and keeps
the rest lowercase.
9
✓ The function takes a string as input.
✓ The .title() method capitalizes the first letter of each word.
✓ The modified string is returned.
Explanation:
✓ The split() method breaks the string into a list of words based on spaces.
This is a list comprehension that processes each word:
✓ word[0].upper() → Converts the first letter of word to uppercase.
✓ word[1:] → Keeps the rest of the word unchanged.
✓ if word else "" → Handles empty strings (avoiding errors).
✓ The " ".join() method joins the list into a single string, adding spaces between words.
16. (i) Write a function to find the number of common characters in two strings.
(ii) Write a program to reverse a string.
(i) Write a function to find the number of common characters in two strings.
Output
Using set Intersection
def common_characters(s1, s2): 3
return len(set(s1) & set(s2)) # Find common unique characters
2
# Example usage
print(common_characters("apple", "grape")) # Output: 3 (a, p, e)
print(common_characters("hello", "world")) # Output: 3 (o, l)
Execution:
10
return s[::-1] # Slice with step -1 to reverse
Explanation:
11
3. Describe the methods and operations of Dictionaries.
14. Recollect the various dictionary operations and explain them with an example.
Dictionaries in Python
1. Creating a Dictionary
Syntax
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}
Key Properties
• Keys must be unique and immutable (e.g., strings, numbers, tuples).
• Values can be of any data type and do not need to be unique.
• Dictionaries are mappings, not sequences, meaning they store objects by key rather than
relative position.
Important Notes
• Keys are case-sensitive: "Key" and "key" are treated as different keys.
• Using a mutable object as a key causes a TypeError.
12
Syntax :
dictionary_name[key]
Example:
student = {"name": "John", "age": 20, "course": "IT"}
print(student["name"]) # Output: John
• In Python, dictionaries allow adding new key-value pairs or modifying existing ones using the
assignment operator (=).
Syntax
dictionary_variable[key] = value
Example
student = {"name": "John", "age": 20}
student["course"] = "IT" # Adding a new key-value pair
print(student)
# Output: {'name': 'John', 'age': 20, 'course': 'IT'}
Deleting all items: Use the .clear() function to remove all key-value pairs but keep the dictionary.
student.clear()
print(student)
# Output: {}
13
Deleting the entire dictionary: Use del to remove the dictionary from memory.
del student
print(student) # This will raise an error since 'student' no longer exists
• Retrieving Keys: The .keys() method returns a list of all dictionary keys in arbitrary order.
Sorting Dictionary Keys: The sorted() function sorts the keys in ascending order.
sorted_keys = sorted(student.keys())
print(sorted_keys)
# Output: ['age', 'course', 'name']
METHODS OF DICTIONARIES
14
15
5. Write a program that takes a sentence as input from the user and computes the frequency of
each letter. Use a variable of dictionary type to maintain the count.
Program
sentence = input("Enter a sentence: ")
frequency = {} Output
for char in sentence: Enter a sentence: Hello World
if char.isalpha():
d : 1
char = char.lower()
e : 1
frequency[char] = frequency.get(char, 0) + 1
h : 1
l : 3
for letter, count in sorted(frequency.items()): o : 2
print(letter, ":", count) r : 1
w : 1
Explanation
16
✓ The dictionary will be used to store the count of each alphabet letter in the given sentence .
✓ for char in sentence:
This iterates through each character in the string sentence.
The loop variable char will take one character at a time from sentence.
✓ if char.isalpha():
This checks if char is an alphabet letter (i.e., it is not a space, number, or punctuation).
The .isalpha() method returns True for alphabet characters (a-z, A-Z) and False for anything
else.
✓ char = char.lower()
Converts char to lowercase to ensure that uppercase and lowercase letters are treated the
same.
✓ frequency[char] = frequency.get(char, 0) + 1
8. Using the concept of dictionary, write a program to create a dictionary that calculates the
frequency of words for a given text.
Program
def word_frequency(text):
word_count = {}
words = text.lower().split()
return word_count
Output
Enter text: hi! Chennai is the capital city of Tamilnadu. Chennai is the hub
for film production and studios.
17
{'hi': 1, 'chennai': 2, 'is': 2, 'the': 2, 'capital': 1, 'city': 1, 'of': 1,
'tamilnadu': 1, 'hub': 1, 'for': 1, 'film': 1, 'production': 1, 'and': 1,
'studios': 1}
Explanation
word_count = {}
✓ Creates an empty dictionary to store word counts.
words = text.lower().split()
✓ Converts all characters to lowercase to ensure case insensitivity.
✓ Splits the text into individual words.
for word in words:
✓ Iterates through each word in the list.
word = word.strip(".,!?;:'\"()")
✓ Cleans punctuation marks from each word.
word_count[word] = word_count.get(word, 0) + 1
✓ word_count is a dictionary that stores words as keys and their frequency as values.
✓ .get(word, 0) checks if word exists in word_count:
✓ If word exists, it returns its current count.
✓ If word does not exist, it returns 0 (default value).
✓ + 1 increases the count by 1.
✓ The updated value is assigned back to word_count[word].
Example
(First appearance of hello)
# word_count.get("hello", 0) → 0 (since "hello" is not yet in
the dictionary)
# 0 + 1 → 1
# word_count now becomes {'hello': 1}
Program
# Initialize an empty dictionary Output
my_dict = {} Added (name: Alice) to dictionary.
18
# Display the dictionary
print("Updated Dictionary:", my_dict)
Explanation
➢ We start with an empty dictionary called my_dict.
➢ def add_element(key, value):
✓ This function takes two parameters: key and value.
✓ It adds the key-value pair to the dictionary.
➢ add_element("name", "Alice")
add_element("age", 25)
add_element("city", "New York")
We call the function three times to add elements.
➢ Finally, we display the dictionary with the newly added elements.
Key Features:
• No Duplicates: Sets automatically remove duplicate values.
• Unordered: The elements in a set do not follow a specific order.
• Mutable: We can add or remove elements from a set.
Usage: Sets are useful when we need to store unique items and perform operations like union,
intersection, and difference efficiently.
1. Creating a Set
A set in Python is created using curly brackets {} or the built-in set() function.
Syntax
set_variable = {val1, val2, ...}
Example
s = {1, 2.0, "abc"}
print(s)
✓ This creates a set containing elements of different data types (integer, float, and string).
Key Features:
✓ A set can store multiple types of data.
✓ It removes duplicate values automatically.
✓ Order of elements is not maintained.
19
No Duplicate Values in Sets
✓ Sets in Python do not allow duplicate values.
✓ If the same element is added multiple times, it is stored only once.
Example
# Creating a set with different data types and duplicate values
s = {1, 2.0, "hello", 2, "hello", 3.5, 2.0} Output
Example
Output
# Define two sets Union: {1, 2, 3, 4, 5, 6, 7, 8}
set1 = {1, 2, 3, 4, 5} Intersection: {4, 5}
set2 = {4, 5, 6, 7, 8} Difference (set1 - set2): {1, 2, 3}
Difference (set2 - set1): {8, 6, 7}
# Union of sets
union_set = set1 | set2 # or use set1.union(set2)
print("Union:", union_set)
# Intersection of sets
intersection_set = set1 & set2 # or use set1.intersection(set2)
print("Intersection:", intersection_set)
20
# Difference of sets (elements in set1 but not in set2)
difference_set = set1 - set2 # or use set1.difference(set2)
print("Difference (set1 - set2):", difference_set)
21
22
13. How to remove items from set? Explain the methods used for it with example.
SET
Definition:
✓ A set is a data structure in Python similar to a list but with no duplicate values.
✓ A set in Python is created using curly brackets {} or the built-in set() function.
Key Features:
• No Duplicates: Sets automatically remove duplicate values.
• Unordered: The elements in a set do not follow a specific order.
• Mutable: We can add or remove elements from a set.
1. remove() Method
• Removes the specified element from the set.
• If the element does not exist, it raises a KeyError.
23
my_set = {1, 2, 3, 4, 5}
my_set.remove(3)
print(my_set) # Output: {1, 2, 4, 5}
2. discard() Method
• Removes the specified element from the set.
• If the element does not exist, it does not raise an error.
my_set = {1, 2, 3, 4, 5}
my_set.discard(3)
print(my_set) # Output: {1, 2, 4, 5}
3. pop() Method
• Removes and returns a random element from the set.
• Since sets are unordered, we cannot predict which element will be removed.
• If the set is empty, it raises a KeyError.
my_set = {1, 2, 3, 4, 5}
removed_item = my_set.pop()
print(removed_item) # Output: (random element)
print(my_set) # Output: Remaining elements after pop
Use when: You just want to remove any item (e.g., when processing all items one-by-one).
Since sets in Python are unordered, the pop() method removes an element without following any
specific order. The element that gets removed depends on how Python internally stores the set's
elements, which can vary between executions.
➢ Each time you run this code, it might remove a different element.
4. clear () Method
• Removes all elements from the set, making it empty.
my_set = {1, 2, 3, 4, 5}
my_set.clear()
print(my_set) # Output: set()
• If you’re not sure whether an item exists in a set and still want to remove it safely, use
discard () instead of remove ().
17. (i) Write a Python program to check if two given sets have no elements in common. (ii) Write a
Python program to remove the intersection of a 2nd set from the 1st set.
24
(i) Write a Python program to check if two given sets have no elements in common.
Program
# Function to check if two sets have no elements in common
def are_disjoint(set1, set2):
# Using isdisjoint() method Output
return set1.isdisjoint(set2)
set_a = {1, 2, 3}
# Example sets set_b = {4, 5}
set_a = {1, 2, 3, 4}
The sets have no elements
set_b = {5, 6, 7}
in common.
If:
# Check if they have no common elements set_a = {1, 2, 3}
if are_disjoint(set_a, set_b): set_b = {2, 4, 6}
print("The sets have no elements in common.")
else: The sets have some
print("The sets have some elements in common.") elements in common.
Explanation
(ii) Write a Python program to remove the intersection of a 2nd set from the 1st set.
✓ It will delete all elements from the first set that are also present in the second set.
Program
# Define two sets Output:
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7} Set1 after removing intersection
with Set2: {1, 2, 3}
# Remove common elements (intersection) from set1
set1.difference_update(set2) Because 4 and 5 are
# Display the result
common to both sets,
print("Set1 after removing intersection with Set2:", set1) they are removed from
set1.
difference_update()
25