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
yUsing index:
for i in range(len(text)):
print(f"position {i}: {text[i]}")Output:
position 0: H
position 1: e
position 2: yChallenge
EasyCreate 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 belowThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 48Loops
For LoopWhile LoopBreakContinueRecap - FactorialThe Range FunctionNested LoopRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators9Functions
Declare a FunctionArgumentsReturnRecap - Sigma FunctionRecap - Validation FunctionDefault Values12Iterating Over Sequences
Iterating Over ElementsThe Enumerate FunctionIterating Over Strings Part 1Iterating Over Strings Part 2