Quick question pls | Sololearn: Learn to code for FREE!

0

Quick question pls

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

1/18/2022 10:42:20 PM

Oyarekhua Sandra

13 Answers

New Answer

+1

x = input() lst = x.split(' ') print(len(lst))

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

0

Ollie Q It's actually an input I want to use it for so the string isn't specific 🥲

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.

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.

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

0

Oyarekhua Sandra print( len(lst)*2 - 1 ) It's a trick I guess. Check if this works!

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

0

Shubham jadhav Could you pls explain the logic behind formula "len(lst)*2-1"?

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

0

Shubham jadhav This would give the sum of word and separator counts. The OP asked for word or letter count.

0

Emerson Prado yeah Do you know how I can get the letter count?

0

Oyarekhua Sandra See my answer from yesterday