Skip to content
Question

Q.(a) Write a function in Python that displays the book names having 'Y' or 'y' in their name from a text file "Bookname.txt". Example : If the file 'Bookname.txt' contains the names of following books : One Hundred Years of Solitude The Diary of a Young Girl On the Road After execution, the output will be : One Hundred Years of Solitude The Diary of a Young Girl

(OR)
(b) Write a function RevString() to read a textfile "Input.txt" and prints the words starting with 'O' in reverse order. The rest of the content is displayed normally. Example : If content in the text file is : UBUNTU IS AN OPEN SOURCE OPERATING SYSTEM Output will be : UBUNTU IS AN NEPO SOURCE GNITAREPO SYSTEM (words 'OPEN' and 'OPERATING' are displayed in reverse order)
CBSECBSE Class XII Board 2023Subjective· 3mImportance★★★★★
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

Part (a): print book names that contain 'Y' or 'y'. Part (b): reverse words that start with 'O'/'o' and print the whole text.

Both parts read a text file and filter/transform its content.

Part (a)

Iterating over a file object yields one line at a time. Each line includes a trailing newline, so strip() cleans it, then the in operator tests for the target character.

def display_books():
    f = open("Bookname.txt", "r")
    for line in f:
        name = line.strip()
        if 'Y' in name or 'y' in name:
            print(name)
    f.close()

For the sample names (One Hundred Years of Solitude / The Diary of a Young Girl / On the Road):

  • "One Hundred Years of Solitude" contains 'Y' (Years) -> printed.
  • "The Diary of a Young Girl" contains 'y'/'Y' (Diary, Young) -> printed.
  • "On the Road" has no 'Y'/'y' -> skipped.

Expected output:

One Hundred Years of Solitude
The Diary of a Young Girl …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.