Kkkk
Kkkk
Kkkk
# Remove any leading/trailing whitespace and split the line into words
words = line.strip().split()
print('#'.join(words))
output:-
Hello#world
This#is#a#test
Python#is#awesome
2. Read a text file and display the number of vowels, consonants, uppercase, and lowercase
characters:
def count_characters_in_file(file_name):
vowels = 'aeiouAEIOU'
consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'
vowels_count += 1
consonants_count += 1
elif char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1
print(f'Vowels: {vowels_count}')
print(f'Consonants: {consonants_count}')
# Usage example
count_characters_in_file('sample.txt')
output:-
Hello World
This is Python
3.Remove all the lines that contain the character 'a' in a file and write it to another file.
outfile.write(line)
# Usage example
remove_lines_with_a('sample.txt', 'output.txt')
output:-
This is a test
Hello world
Python is fun
4.Create a binary file with name and roll number. Search for a given roll number and display the
name.
import pickle
def create_binary_file():
data = [
(101, 'Alice'),
(102, 'Bob'),
(103, 'Charlie')
def search_roll_number(roll_number):
students = pickle.load(file)
if roll == roll_number:
return
# Usage example
create_binary_file()
search_roll_number(102)
output:-
5.Create a binary file with roll number, name, and marks. Input a roll number and update the marks
import pickle
def create_marks_file():
data = [
pickle.dump(data, file)
students = pickle.load(file)
if roll == roll_number:
break
else:
return
pickle.dump(students, file)
# Usage example
create_marks_file()
update_marks(102, 95)
output:-
Marks updated for roll number 102.
6.Write a random number generator that generates random numbers between 1 and 6 (simulating a
dice)
import random
def roll_dice():
return random.randint(1, 6)
# Usage example
output:-
class Stack:
def __init__(self):
self.stack = []
self.stack.append(item)
def pop(self):
if len(self.stack) > 0:
return self.stack.pop()
else:
print("Stack is empty!")
return None
def peek(self):
if len(self.stack) > 0:
return self.stack[-1]
else:
print("Stack is empty!")
return None
def is_empty(self):
return len(self.stack) == 0
def size(self):
return len(self.stack)
# Usage example
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop()) # Output: 3
print(stack.peek()) # Output: 2
output:-
3
8.Create a CSV file by entering user-id and password, read and search the password for a given user-
id
import csv
def create_csv_file():
users = [
['user1', 'password1'],
['user2', 'password2'],
['user3', 'password3']
writer = csv.writer(file)
writer.writerows(users)
def search_password(user_id):
reader = csv.reader(file)
if row[0] == user_id:
return
create_csv_file()
search_password('user2')
output:-