Looping Over Strings

For Loops

Looping Over Strings

In this tutorial, we'll process text one character at a time.

A string is a sequence of characters, so you can loop over it.

word = "python"

for letter in word:
    print(letter)

Output:

p
y
t
h
o
n

Counting Characters

Loops are useful when you want to inspect each character:

word = "banana"
count = 0

for letter in word:
    if letter == "a":
        count = count + 1

print(count)

Output:

3

The loop checks each letter. When the letter is "a", the counter increases.

Building a New String

You can build a result as you loop:

word = "hello"
result = ""

for letter in word:
    result = result + letter.upper()

print(result)

Output:

HELLO

Checking Each Character

You can use conditions inside the loop:

word = "Python3"

for character in word:
    if character.isdigit():
        print("Found a number:", character)

This is a useful pattern for validation and text processing.

Common Mistake

Spaces are characters too:

message = "hi there"

for character in message:
    print(character)

The loop will visit the space between hi and there.

Practice

Ask Python to count how many vowels are in the word "development".