Iterate over characters of a string in Python
Last Updated : 27 Oct, 2024
Improve
In this article, we will learn how to iterate over the characters of a string in Python. There are several methods to do this, but we will focus on the most efficient one. The simplest way is to use a loop. Let’s explore this approach.
Using for loop
The simplest way to iterate over the characters in a string is by using a for loop. This method is efficient and easy to understand.
s = "hello"
for char in s:
print(char)
Output
h e l l o
Explanation: for char in s: This line loops through the string s, with char representing each character in s one by one.
Using enumerate for Index Access
If we need both the character and its index then enumerate() is a great choice. It returns both values in each iteration.
s = "hello"
for i, char in enumerate(s):
print(f"Index {i}: {char}")
Output
Index 0: h Index 1: e Index 2: l Index 3: l Index 4: o
Explanation:
- enumerate(s) provides both the index i and the character char.
- The print function uses a formatted string, where the f before the string allows us to include variables directly within it using curly braces {}.