CBSE Class 12 Computer Science Question 32 of 43

Practice Paper — Question 3

Back to all questions
3
Question

Question 28(a)

Write a function begEnd() in Python to read lines from text file 'TESTFILE.TXT' and display the first and the last character of every line of the file (ignoring the leading and trailing white space characters).

Example: If the file content is as follows:

An apple a day keeps the doctor away.
We all pray for everyone's safety
A marked difference will come in our country.

Then begEnd () function should display the output as: A. Wy A.

Solution
def begEnd():
    file = open('TESTFILE.TXT', 'r')
    f = file.readlines()
    for line in f:
        line = line.strip()  
        if line:  
            first_char = line[0]
            last_char = line[-1]
            print(first_char + last_char, end=' ')  
begEnd()
Output
A. Wy A.
Answer