Quick question pls | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Quick question pls

How do I count the number of words in a sentence?

18th Jan 2022, 10:42 PM
Oyarekhua Sandra
13 Answers
+ 1
x = input() lst = x.split(' ') print(len(lst))
20th Jan 2022, 5:48 PM
Shubham jadhav
Shubham jadhav - avatar
0
Hi Oyarekhua Sandra, You could split the string at “” and then i believe call the len() function on the resulting array should get the number of words in the sentence
18th Jan 2022, 10:48 PM
Ollie Q
Ollie Q - avatar
0
Ollie Q It's actually an input I want to use it for so the string isn't specific 🥲
18th Jan 2022, 11:42 PM
Oyarekhua Sandra
0
Use split function. Don't specify "" as separator - this would split at every character - but leave the default - white space(s) - which suits perfectly word splitting. Then count with len function.
19th Jan 2022, 4:21 AM
Emerson Prado
Emerson Prado - avatar
0
Shubham jadhav Pls avoid giving finished code as answer. Prefer hints that guide the asker to find the solution him/herself. Follow hints and find solutions makes one learn for real.
20th Jan 2022, 10:53 PM
Emerson Prado
Emerson Prado - avatar
0
Shubham jadhav Pls what if I want to count the letters still excluding the spaces. I tried using 'count' instead of Len but it's showing error
21st Jan 2022, 5:19 PM
Oyarekhua Sandra
0
Oyarekhua Sandra print( len(lst)*2 - 1 ) It's a trick I guess. Check if this works!
21st Jan 2022, 5:31 PM
Shubham jadhav
Shubham jadhav - avatar
0
You can either: 1. Remove spaces from string then using len on the resulting string 2. Split words in the same way, then summing all words lengths
22nd Jan 2022, 3:00 AM
Emerson Prado
Emerson Prado - avatar
0
Shubham jadhav Could you pls explain the logic behind formula "len(lst)*2-1"?
22nd Jan 2022, 3:02 AM
Emerson Prado
Emerson Prado - avatar
0
Emerson Prado String = "Hello Emerson Prado" See, a string has (3) words if we separate on spaces. --> [len()] And how many separators are there (3-1). --> [len()-1] Hence, the formula --> len() + len() -1 --> 2*len()-1
22nd Jan 2022, 3:31 AM
Shubham jadhav
Shubham jadhav - avatar
0
Shubham jadhav This would give the sum of word and separator counts. The OP asked for word or letter count.
23rd Jan 2022, 1:35 PM
Emerson Prado
Emerson Prado - avatar
0
Emerson Prado yeah Do you know how I can get the letter count?
23rd Jan 2022, 1:43 PM
Oyarekhua Sandra
0
Oyarekhua Sandra See my answer from yesterday
23rd Jan 2022, 7:07 PM
Emerson Prado
Emerson Prado - avatar