Practice Question 26
In this question, we will learn how to write a function that extracts words that end in a number, such as “User1”, “Batch2026”, or “Point5”.
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
To check the end of a word, we use Python’s powerful negative indexing:
-
Read and Split: We open
info.txtand break the content into individual words. -
Target the Last Character: In Python,
word[-1]always refers to the very last character of a string, no matter how long the word is. -
The
isdigit()Check: We apply the.isdigit()method to only that last character. -
Display: If the condition is met, we print the word.
Let’s Code as per the above logic :
def displayWordsEndingWithDigit():
f = open("info.txt", "r")
data = f.read()
wordlist = data.split()
print("Words ending with a digit:")
for word in wordlist:
# Check if the word is not empty and the last character is a digit
if word and word[-1].isdigit():
print(word)
f.close()
# To call the function:
displayWordsEndingWithDigit()
Important Notes for Students
As a teacher, I want you to focus on these three key points so you don’t lose marks:
-
-
Negative Indexing: Using
word[-1]is much better than usingword[len(word)-1]. It is cleaner, faster, and follows Python’s “best practices.” -
Safety Check: Notice the
if word and ...part. This ensures that if there are empty strings in your list (which can happen with certain splitting scenarios), the program won’t crash when trying to access index-1. -
Digits vs. Numbers: Remember that
isdigit()checks for a single character (0-9). If the word ends in “123”,word[-1]will correctly identify ‘3’ as a digit.
-
Teacher’s Secret Tip for Exams:
If the examiner asks for words Starting with a digit, simply change word[-1] to word[0]. The rest of the logic remains exactly the same!
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!