Count Number of Words in a String Dry Run in PYTHON

Count Number of Words in a String is an interactive PYTHON dry run visualizer from the Strings programs section. Study the source code, then use the execution controls to follow each step, variable update, highlighted line, and console output.

This page provides a browser-based dry run with source-code highlighting, auto-scroll, voice narration controls, and execution output for learning the program step by step.

Count Number of Words in a String Program Code

# Python program to count words in a string
text = "  Hello   world!  Python programming.  "

# Method 1: Using split() (simplest)
words1 = text.split()
count1 = len(words1)

# Method 2: Manual counting
count2 = 0
in_word = False
for char in text:
    if char.isspace():
        in_word = False
    elif in_word == False:
        in_word = True
        count2 = count2 + 1

# Method 3: Using regular expressions
import re
words3 = re.findall(r'\b\w+\b', text)
count3 = len(words3)

print("Original text:", repr(text))
print("Word count (split):", count1)
print("Word count (manual):", count2)
print("Word count (regex):", count3)
print("Words found:", words1)

View the complete Strings programs page.

Program Console Count Number of Words in a String Topic: PYTHON Vignaankosh.com
Execution Panel
Step 0/0
Console is empty.