CBSE · 083Class XII · 2023Section C3 marks

Question 27(2)

30 March 2023 · Computer Science (083)

Write a function count_Dwords() in Python to count the words ending with a digit in a text file "Details.txt".

Example: If the file content is :

text
On seat2 VIP1 will sit and
On seat1 VVIP2 will be sitting

The output should be :

text
Number of words ending with a digit are 4

Answer

python
def count_Dwords():
    count = 0
    with open("Details.txt", 'r') as F:
        S = F.read()
        Wlist = S.split()
        for W in Wlist:
            if W[-1].isdigit():
                count += 1
    print("Number of words ending with a digit are", count)

Explanation

Reads the file, splits the contents into words on whitespace, and checks the last character of each word with isdigit().