How to Iterate Python Strings: 3 Methods
In Python, strings are iterable objects that can be looped through to access each character. One can use a for loop to iterate through the characters in a string, or use indexes to access specific characters. Additionally, the built-in enumerate() function can be used to retrieve both the index and value of each character at the same time. Here are some examples of methods for iterating through a string:
Iterate through each character in the string using a for loop.
s = "Hello, World!"
for char in s:
print(char)
2. Accessing specific characters using an index:
s = "Hello, World!"
for i in range(len(s)):
print(s[i])
3. Use the enumerate() function to get both the index and value of characters simultaneously.
s = "Hello, World!"
for i, char in enumerate(s):
print(f"Index {i}: {char}")
These are common methods for traversing strings, and you can choose the appropriate method to process strings based on specific needs.