Practice Question 11
In this question, we will learn how to write a function that counts how many lines in a text file end with a full stop (.). This logic is excellent for understanding how Python handles line breaks and list indexing.
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
We are going to treat the file as a list of lines and check the last position of each string. Here is the breakdown:
-
Read into a List: We use
f.readlines()to grab every line and store it in a variable calledlinelist. -
The Loop: We go through
linelistone line at a time. -
The “Hidden” Character Check: In Python files, lines usually end with
\n. To find the real last character (the full stop), we use.strip()to remove that hidden newline. -
Negative Indexing: We use
line[-1]to look at the very last character of the cleaned-up line.
Let’s Code as per the above logic :
def countFullStopLines():
f = open("report.txt", "r")
# readlines() returns a list where each element is one line
linelist = f.readlines()
count = 0
for line in linelist:
# We strip() to remove the hidden '\n' at the end of the line
line = line.strip()
# Check if the line is not empty and the last character is '.'
if len(line) > 0 and line[-1] == '.':
count += 1
f.close()
return count
# To call the function and see the result:
print("Number of lines ending with a full stop:", countFullStopLines())
Important Notes for Students
This is a very common logic, but here is why we added the .strip():
-
The Newline Trap: If your line is
"Hello world.\n", thenline[-1]is actually\n. By usingline.strip(), the line becomes"Hello world.", and nowline[-1]correctly identifies the.. -
Handling Empty Lines: If there is a blank line in your file,
line[-1]might cause an error because there is no character at index -1. Addingif len(line) > 0makes your code “crash-proof.” -
Indexing: Using
[-1]is a smart Python shortcut to get the last character without needing to calculate the length of the string manually.
Teacher’s Secret Tip for Exams:
If you are asked to check the first character of a line, use line[0]. If you are asked to check the last character, use line[-1]. This simple indexing trick saves a lot of time!
Want to practice more? If you found this helpful, I have compiled a full list of 30 practice problems just like this one. Each question focuses on a different logic to help you become a pro at File Handling.
Click here to view the full 30-Question Practice Set
Exam Special Recommendation: If you are studying in 12th class and preparing for your board exam, then go for the “Computer Science with Python Sample Paper Book“. It contains 3 previous years’ papers and 7 practice papers solved strictly as per the CBSE pattern. Click here to purchase your copy!