Q1. Write a program to input a string and count the occurrence of the word ‘the’(in any case) in the string.
For eg: if the input is:Â The sun rises in the east.
Output should be:2
Q2. Write a program to input a string and count the number of words in it.                       Â
For eg: if the input is: I like computer science.
Output should be:4
Q3. Write a program to input a string and print at which position a particular word exist. Â Â Â Â Â Â Â Â Â Â Â Â Â
For example :if the string is: I like computer science.
Word is:like(to be taken from user)
Output is 2 (as like is the second word in the string.)
Q1)
user_str = input('Enter in your string')
count = 0
# split the string into words, space separator
words = user_str.split(' ')
# counting the number word 'the'
for word in words:
if word ='the':
count += 1
print(count)
Q2)
user_str = input('Enter in your string')
count = 0
# split the string into words, space separator
words = user_str.split(' ')
for word in words:
# do not count the space as a word
if word != '':
count += 1
print(count)
Q3)
user_str = input('Enter in your string')
user_word = input('Enter in your word')
position = 0
# split the string into words, space separator
words = user_str.split(' ')
for word in words:
# the position of the word in the string, excluding spaces
if word != '':
position += 1
# print positions of the selected word on one line separated by a space
if word == user_word:
print(position, end=' ')
Comments
Leave a comment