Display all words starting with a vowel and ending with a digit

Problem

Write a python program to display all words starting with a vowel and ending with a digit in a text file.

Please check file handling in python if you don't familiar with working with files in python.

Solution

Step 1: First, open the text file

Step 2: Read the file content and store it in a variable

Step 3: Split the whole content based on a new line('\n')

Step 4: Use a for loop to iterate the content

Step 5: Split each word based on spaces in a line

Step 6: Check if the first letter of the word is a vowel and the last letter is a digit or not

Step 7: If step 6 returns 'True', print the result  

Example

The input file looks like.

A text file containing several text lines - PySeek

Code


def checkDigit(d):
return d in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']

def checkVowel(ch):
ch = str(ch)
# Return True, if the character is found in the list
return ch.lower() in ['a', 'e', 'i', 'o', 'u']

with open('file.txt') as f:
content = f.read()

content = content.split("\n")

for ix in content:
if ix:
for word in ix.split():
# checking the first and the last letter of every word
if checkVowel(word[0]) and checkDigit(word[-1]):
print(word)

Output

user5

Act

Exercise

☛Solve the same problem but in this case, the last letter of the letter will be a consonant.

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post