How to count words in a string in python

 Que - How to count words in a string?

Ans- In python we are using str_name.count("letter/words") function to count the words/letters in a string. By the help of this function we can count words, letter, sentences in string.

Now we see some easy examples to understand better how this function works:-

Example (1):-

Steps to write this below program:-
  1. In first step we define a variable (Str) and take input by using input function.
  2. In next step we define another variable (Count) in this we take input of which letter words or sentence is to be count.
  3. In next step we use str_name.count("letter/words") to count words letter or sentences in a string.
  4. In last step we print the value by using print function. 

#counting letter/ words in a program
Str=input("enter a sentence :- ")
Count=input("enter letter/words to count in string :-")
Count=Str. count(Count)
print("Total words/letter :- ",Count)

Result:-


Example (2):- For replace function practice. Try it yourself without looking at the solution. 

Que - One day two friends Dhruv and Rahul are playing typing games together on there computers and Rahul said that I am very fast in typing so dhruv take a test of rahul speed typing. Dhruv given a sentence to Rahul and tell him to type without stopping his fingers. And Rahul done his work complete and when they check the sentence is correct or not they find some extra words in the sentence. So can you help Rahul so that he correct the sentence which he type .

Solution:-
Steps to solve the question:-
  1. In first step we define a variable (Str) and take input using input function.
  2. In next step we define a variable (Count) that count the extra word to be remove from the sentence so we take input by using input function.
  3. In next step we use str_name.replace("change letter"," replace letter") .
  4. In last step we use print function to print the required solution.

Syntax and solution:-

Str=input("enter a sentence :-")
Count=input("enter a word to remove :-")
Str=Str.replace(Count," ")
print(Str)

Result:-




Post a Comment

Previous Post Next Post