KnowledgeBoat Logo
|

Computer Science

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.

Python

Python File Handling

2 Likes

Answer

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.

Answered By

1 Like


Related Questions