Answer to Question #162989 in Python for Ruturaj

Question #162989

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.)




1
Expert's answer
2021-02-11T16:58:00-0500

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=' ')  
    

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS