Home > Courses > Python > Introduction to Python

5 ways to iterate a string in Python

Last updated : April 1, 2023

There are several ways to iterate through a string in Python. This article explains the five most common ways to do that.

1. Using a for loop.

This is the easiest and most common way to iterate through a string. The code iterates through each character in the string.

string = "Welcome to LearnBestCoding!" 
for char in string: 
	print(char)

2. Using a while loop.

Using a while loop with an index to iterate a string in Python is helpful in certain situations where I want more control over the iteration process, such as:

  • When I need to access the index of the current character.
  • When I need to change the index within the loop based on specific conditions.
  • When I want to perform certain actions or checks before or after accessing the character at a particular index.

Below is the basic while loop format to iterate a string.

string = "Welcome to LearnBestCoding!" 
index = 0 
while index < len(string): 
	print(string[index]) # print the char at the index
	index += 1 # increment the index before the next iteration

Here is an example of taking certain actions based on specific conditions. I exit the loop after encountering "t" in the string.

string = "Welcome to LearnBestCoding!" 
index = 0 
while index < len(string): 
	print(string[index]) # print the char at the index 
	if string[index] == "t": 
		break
	index += 1 # increment the index before the next iteration

3. Using a for loop with enumerate() function.

The enumerate() function iterates over a sequence (like a list, tuple, or string) and keeps track of the index and the element at that index.

string = "Welcome to LearnBestCoding!" 
for index, char in enumerate(string, start=1):
    print(f"Character at index {index}: {char}")
    if index == 10:
        break

4. Using a list comprehension.

This method allows me to generate a new list by applying an expression to each character in the string using a single line of code.

string = "Welcome to LearnBestCoding!" 
vowels = "aeiou"
vowels_in_name = [char for char in string if char.lower() in vowels]
print(vowels_in_name)

5. Using a for loop with the range() function.

Here I use the length of the word, then loop through the size and access each character by their index. It is similar to the standard for loop but allows some flexibility to play with the length etc.

string = "Welcome to LearnBestCoding!" 
for i in range(int(len(string)/2)):
    print(string[i])
L Raney
By: L Raney
Lance is a software engineer with over 15 years of experience in full-stack software development.
Read more...

Comments are disabled

No Comments