Iterate over characters of a string in Python
In Python, while operating with String, one can do multiple operations on it. Let’s see how to iterate over characters of a string in Python.
Example #1: Using simple iteration and range()
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
# Python program to iterate over characters of a string # Code #1string_name = "geeksforgeeks" # Iterate over the stringfor element in string_name: print(element, end=' ')print("\n") # Code #2string_name = "GEEKS" # Iterate over indexfor element in range(0, len(string_name)): print(string_name[element]) |
g e e k s f o r g e e k s G E E K S
Example #2: Using enumerate() function
# Python program to iterate over characters of a string string_name = "Geeks" # Iterate over the stringfor i, v in enumerate(string_name): print(v) |
G e e k s
Example #3: Iterate characters in reverse order
# Python program to iterate over characters of a string # Code #1string_name = "GEEKS" # slicing the string in reverse fashion for element in string_name[ : :-1]: print(element, end =' ')print('\n') # Code #2string_name = "geeksforgeeks" # Getting length of stringran = len(string_name) # using reversed() functionfor element in reversed(range(0, ran)): print(string_name[element]) |
S K E E G s k e e g r o f s k e e g
Example #4: Iteration over particular set of element.
Perform iteration over string_name by passing particular string index values.
# Python program to iterate over particular set of element.string_name = "geeksforgeeks" # string_name[start:end:step]for element in string_name[0:8:1]: print(element, end =' ') |
g e e k s f o r


