Menu
Coddy logo textTech

Iterating Over Strings Part 1

Part of the Fundamentals section of Coddy's Python journey — lesson 62 of 77.

Similar to lists, you can iterate over strings:

text = "Hey"
for char in text:
    print(char)

Output:

H
e
y

Using index:

for i in range(len(text)):
    print(f"position {i}: {text[i]}")

Output:

position 0: H
position 1: e
position 2: y
challenge icon

Challenge

Easy

Create a program that receives a string as input, and it prints how many times the character p (or P) is in the string.

Some chars might be uppercase, use char.lower() to convert it to lowercase.

Cheat sheet

Iterating over strings in Python:

# Using for loop
text = "Hey"
for char in text:
    print(char)

# Using index
for i in range(len(text)):
    print(f"position {i}: {text[i]}")

Convert character to lowercase:

char.lower()

Try it yourself

text = input()
# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals