Iterate over characters of a string in Python
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 {}.
Frequently Asked Questions (FAQs)
How do I get both the character and its index in a string?
Use the enumerate() function, which provides both the index and the character as you iterate.
Can I change characters while iterating over a string?
No, strings in Python are immutable. However, you can create a new modified string by building a list of characters and then joining them together.
How can I store each character as an element in a list?
You can use list comprehension to create a list where each character in the string becomes a separate element.