In this blog post, I will walk you through the process of writing a Python program that prints all the odd-length words in a given string.
Understanding the Problem
Before diving into the code, let's understand the problem statement. We are given a string, and our task is to extract and print all the words from the string that have an odd length. For example, if the input string is "Hello, how are you?", the program should print the words "Hello" and "you".
Now, let's write the Python code to solve this problem step by step.
Accepting User Input
First, we need to accept a string from the user. We can use the input() function for this. Let's define a variable called "sentence" and assign it the value entered by the user.
string = input("Enter a sentence: ")
Splitting the String into Words
Next, we need to split the input sentence into individual words. We can use the split() method, which splits a string into a list of words based on the whitespace character.
words = string.split()
Filtering Odd-Length Words
Now that we have a list of words, we can iterate over each word and check if its length is odd. If it is, we can print the word.
for word in words:
if len(word) % 2 != 0:
print(word)
Complete Python Program
string = input("Enter a sentence: ")
words = string.split()
print("Odd-length words in the sentence:")
for word in words:
if len(word) % 2 != 0:
print(word)
Output 1:
Enter a sentence: Hello, how are you?
Odd-length words in the sentence:
Hello
you
Output 2:
Enter a sentence: The quick brown fox jumps over the lazy dog
Odd-length words in the sentence:
The
fox
over
the
dog
Conclusion:
In this blog post, we learned how to write a Python program that prints all the odd-length words in a given string. By following the step-by-step process, we were able to successfully solve the problem.
The program accepts a sentence from the user, splits it into individual words, and then filters out the words with an odd length.
Finally, it prints the odd-length words on the console. I hope this tutorial was helpful, and you can now apply this knowledge to solve similar problems in your own Python projects.
0 Comments