Python program to print the words starting with s or S from a text file

 Python program to print the words starting with s or S from a text file

In this example, you will know how to read lines from text file word by word and then check the required condition to print words starting from letter "s".



Logic and Explanation

For the above problem, we first have to open the text file in read mode in our python program. In my example, I am taking a text file name "content.txt" which is present in the same directory where this python file is present. So, I just written the name of file otherwise you have to write the complete path of the file to open the file. This is the code to open file in read mode.


f = open("content.txt","r")


Now, we will read the content of the file by iterating through the content of the file word by word. For this we will first read the whole text file in the form a string. Here, I am reading the text file using f.read() function and storing the text inside the file in a string variable "data".

data = f.read()

Now, for iterating word by word by we will use the below command. Here, we split the data string with spaces. We can split with any string by default it is set to space.


for word in data.split():

Now we will check for the condition that whether the words starts from s or not. First we will access first letter of word using index zero. Then, we will lower that letter and we will check whether it is equal to small "s" or not.  If yes, then we will print that word.


if word[0].lower() == "s":
    print(word)

Complete source code the question is given below. I hope the explanation and the logic of the program is clear to you. In case of any doubt, you can ask in the comments below.


Source Code


f = open("content.txt","r")
data = f.read()
for word in data.split():
    if word[0].lower() == "s":
        print(word)
For example, the content in my content.txt file is shown below.

Hello everyone
My name is Bhavik Agarwal
Like the post
Subscribe my Youtube channel
Share the content
Thanks for coming


Output on running the above program will be

Subscribe
Share


If you like the content, share it in your social media platforms so that we can help the maximum. If you have any query then feel free to ask in the comments below.

We are ready to help you.


Check Similar Programs Here - Python Programs - Question and Answers

Enjoy Coding!!!

For any doubts feel free to ask in comments below.
Stay Connected to Us for more such Courses and Projects.

Post a Comment

For any doubts feel free to ask in comments below.
Stay Connected to Us for more such Courses and Projects.

Post a Comment (0)

Previous Post Next Post