PYTHON PRACTICAL SET-B
Q1. PYTHON : (8 marks)
(i)
Write
a program to print number of special characters in the input string. (3)
Answer:
# Function to count special characters in a string
def count_special_characters(text):
count = 0
for char in text:
# Check if the character is not a letter, digit, or space
if not char.isalnum() and char != " ":
count += 1
return count
# Get input from the user
user_input = input("Enter a string: ")
special_count = count_special_characters(user_input)
print("Number of special characters:", special_count)
(ii) Write a program to read from a text file named “poem.txt” and count number of times “my” appears in the file. File is: “my name is manoj. me and my friend went to play cricket”
Answer:
# Function to count occurrences of "my" in the file
def count_my_occurrences(filename: str) -> int:
file = open(filename, "r")
text = file.read().lower() # Convert to lowercase for case-insensitive search
file.close() # Ensure the file is closed after reading
return text.split().count("my")
# Call the function and display the result
occurrences = count_my_occurrences("poem.txt")
print(f"The word 'my' appears {occurrences} times in the file.")
Q.2)
No comments:
If you have any doubt so you can comment me then i will 100% help you ,Through comment Chat