Count words in a given string | Python3 program to count words in a given string ; Returns number of words in string ; word count ; Scan all characters one by one ; If next character is a separator , set the state as OUT ; If next character is not a word separator and state is OUT , then set the state as IN and increment word count ; Return the number of words ; Driver Code
OUT = 0 NEW_LINE IN = 1 NEW_LINE def countWords ( string ) : NEW_LINE INDENT state = OUT NEW_LINE wc = 0 NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if ( string [ i ] == ' ▁ ' or string [ i ] ==   ' ' ▁ or ▁ string [ i ] ▁ = = ▁ ' 	 ' ) : NEW_LINE INDENT state = OUT NEW_LINE DEDENT elif state == OUT : NEW_LINE INDENT state = IN NEW_LINE wc += 1 NEW_LINE DEDENT DEDENT return wc NEW_LINE DEDENT string =   " One two three NEW_LINE INDENT four five   " NEW_LINE DEDENT print ( " No . ▁ of ▁ words ▁ : ▁ " + str ( countWords ( string ) ) ) NEW_LINE