Char can iterate using a for loop in Python. Let’s see how to iterate over characters of a string in Python.
Just iterate through the string:-
a_string="abcd"
for letter in a_string:
print letter
Python for char in string Example
Simple example code python program to iterate over characters of a string
str1 = "Python"
# Code 1
for element in str1:
print(element, end=' ')
print("\n")
# Code 2
str2 = "Code"
for element in range(0, len(str2)):
print(str2[element])
Output:
Another Example
Using enumerate() function.
str1 = "Python"
for i, v in enumerate(str1):
print(v, i)
Output:
P 0
y 1
t 2
h 3
o 4
n 5
Do comment if you have any doubts and suggestions on this Python char topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.