Back to Python
2025-12-195 min read

Example: Loop Through a String (Python Programming)

Learn Example: Loop Through a String (Python Programming) step by step with clear examples and exercises.

Title: Loop Through a String (Python Programming)

Why This Matters

In this lesson, we'll learn how to loop through a string in Python, which is an essential skill for manipulating and analyzing text data. By understanding loops, you can perform various operations like finding specific characters, counting the occurrence of words, or even reversing a string. This knowledge will be beneficial when working on projects that involve text processing, such as web scraping, natural language processing, and data analysis.

Prerequisites

To follow this lesson, you should have a basic understanding of Python programming concepts:

  • Variables and data types
  • Basic operators (e.g., arithmetic, comparison)
  • Control flow statements (if-else)

Core Concept

Iterating through a string using a for loop

Python strings are iterable objects, meaning you can loop through them to access each character one by one. To do this, we use the for loop with an assignment statement that assigns the current character to a variable (usually named char or c). Here's an example:

my_string = "Hello, World!"
for char in my_string:
print(char)

Output:

H
e
l
l
o
,

W
o
r
l
d
!

In the example above, the my_string variable contains a string with spaces and punctuation. The for loop iterates through each character in the string, printing them out one by one.

Looping through a string and performing operations

Now that you know how to loop through a string, we can perform various operations on each character. Here's an example where we count the number of vowels in a given string:

my_string = "This is a sample string."
vowel_count = 0

for char in my_string:
if char.lower() in "aeiou":
vowel_count += 1

print("Number of vowels:", vowel_count)

Output:

Number of vowels: 5

In this example, we initialize a counter variable vowel_count to zero. Inside the for loop, we check if the current character is a vowel (using the lowercase version to account for both uppercase and lowercase letters). If it is, we increment the counter. Finally, we print the total count of vowels found in the string.

Looping through a string using indexing

While iterating through a string with a for loop gives us each character, it doesn't provide access to their positions (indices). To get the indices and perform operations based on them, we can use the built-in enumerate() function. This function returns an iterator that produces tuples containing both the index and the value for each item in the iterable:

my_string = "Hello, World!"
for index, char in enumerate(my_string):
print("Index:", index, "Character:", char)

Output:

Index: 0 Character: H
Index: 1 Character: e
Index: 2 Character: l
Index: 3 Character: l
Index: 4 Character: o
Index: 5 Character: ,
Index: 6 Character: W
Index: 7 Character: o
Index: 8 Character: r
Index: 9 Character: l
Index: 10 Character: d
Index: 11 Character: !

In this example, we use enumerate() to loop through the string and print both the index and character for each iteration. This can be useful when you need to access specific characters or manipulate them based on their positions in the string.

Worked Example

Let's write a Python program that loops through a given string, removes all vowels (including uppercase and lowercase), and prints the resulting string:

def remove_vowels(input_string):
vowels = "aeiouAEIOU"
result = ""

for char in input_string:
if char not in vowels:
result += char

return result

my_string = "This is a sample string."
print("Original String:", my_string)
print("String without vowels:", remove_vowels(my_string))

Output:

Original String: This is a sample string.
String without vowels: Ths s prbl stng.

In this example, we define a function called remove_vowels(), which takes an input string and returns a new string with all vowels removed. We create a list of vowels (both uppercase and lowercase) and initialize an empty result string. Inside the for loop, we check if the current character is not in our vowel list. If it isn't, we add it to the result string. Finally, we print both the original string and the modified string without vowels.

Common Mistakes

  1. Forgetting to handle uppercase vowels when removing them from a string:
def remove_vowels(input_string):
result = ""

for char in input_string:
if char not in "abcdefghijklmnopqrstuvwxyz":
result += char

return result

Solution: Include uppercase vowels in the list of characters to remove.

  1. Not accounting for spaces and punctuation when counting vowels or removing them from a string:
def count_vowels(input_string):
vowel_count = 0

for char in input_string:
if char in "abcdefghijklmnopqrstuvwxyz":
vowel_count += 1

return vowel_count

Solution: Include spaces and punctuation when checking the character to ensure that they are not counted as vowels.

Practice Questions

  1. Write a Python function called reverse_string() that takes an input string and returns the reversed version of it (e.g., "Hello" becomes "olleH").
  2. Write a Python program that finds all palindromes (words that read the same forwards and backwards) in a given list of words.
  3. Write a Python function called find_longest_word() that takes an input string and returns the longest word found within it. If there are multiple words with the same length, return any one of them.
  4. Write a Python program that counts the number of occurrences of each letter in a given string (including spaces).
  5. Write a Python function called is_anagram() that checks if two input strings are anagrams (i.e., they contain the same letters, but possibly in a different order).

FAQ

--

How can I loop through a string and perform an operation on every other character?

You can use the modulus operator (%) to skip characters when iterating through the string. Here's an example:

my_string = "Hello, World!"
for index, char in enumerate(my_string):
if index % 2 == 0:
print("Even index:", char)

How can I loop through a string and perform an operation on every third character?

You can modify the example from question 1 to skip three characters at a time by using the modulus operator (%) with 3:

my_string = "Hello, World!"
for index, char in enumerate(my_string):
if index % 3 == 0:
print("Third character:", char)
Example: Loop Through a String (Python Programming) | Python | XQA Learn