0
0
Pythonprogramming~5 mins

Iterating over strings in Python

Choose your learning style9 modes available
Introduction
Iterating over strings lets you look at each letter one by one. This helps when you want to check or change parts of a word or sentence.
Counting how many times a letter appears in a word.
Changing all letters in a sentence to uppercase or lowercase.
Finding if a certain letter or symbol is inside a word.
Printing each letter of a word on a new line.
Syntax
Python
for letter in string:
    # do something with letter
The word 'string' is the name of your text variable.
Each 'letter' is one character from the string, one at a time.
Examples
Prints each letter of the word 'hello' on its own line.
Python
word = "hello"
for letter in word:
    print(letter)
Prints each letter in uppercase.
Python
text = "Python"
for char in text:
    print(char.upper())
Counts how many times the letter 'a' appears, ignoring case.
Python
name = "Anna"
count_a = 0
for ch in name:
    if ch == 'a' or ch == 'A':
        count_a += 1
print(count_a)
Sample Program
This program prints each letter in the sentence except spaces.
Python
sentence = "Hello World"
for letter in sentence:
    if letter != ' ':
        print(letter)
OutputSuccess
Important Notes
Strings are like a list of letters, so you can use a loop to go through them.
Spaces and punctuation are also characters and will be included unless you skip them.
You cannot change letters directly in a string because strings are fixed, but you can build a new string.
Summary
Use a for loop to look at each letter in a string one by one.
You can check, count, or print letters inside the loop.
Remember that strings cannot be changed directly, but you can create new strings from letters.