There are several ways to iterate through a string in Python. This article explains the five most common ways to do that.
This is the easiest and most common way to iterate through a string. The code iterates through each character in the string.
Using a
Below is the basic
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
The
string = "Welcome to LearnBestCoding!"
for index, char in enumerate(string, start=1):
print(f"Character at index {index}: {char}")
if index == 10:
break
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)
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