Skip to content
Related Articles
Open in App
Not now

Related Articles

Iterate over characters of a string in Python

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 30 Dec, 2022
Improve Article
Save Article

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() 

Python3




# Python program to iterate over characters of a string
 
# Code #1
string_name = "geeksforgeeks"
 
# Iterate over the string
for element in string_name:
    print(element, end=' ')
print("\n")
 
 
# Code #2
string_name = "GEEKS"
 
# Iterate over index
for element in range(0, len(string_name)):
    print(string_name[element])

Output:

g e e k s f o r g e e k s 

G
E
E
K
S

  Example #2: Using enumerate() function 

Python3




# Python program to iterate over characters of a string
 
string_name = "Geeks"
 
# Iterate over the string
for i, v in enumerate(string_name):
    print(v)

Output:

G
e
e
k
s

  Example #3: Iterate characters in reverse order 

Python3




# Python program to iterate over characters of a string
 
# Code #1
string_name = "GEEKS"
 
# slicing the string in reverse fashion
for element in string_name[ : :-1]:
    print(element, end =' ')
print('\n')
 
# Code #2
string_name = "geeksforgeeks"
 
# Getting length of string
ran = len(string_name)
 
# using reversed() function
for element in reversed(range(0, ran)):
    print(string_name[element])

Output:

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. 

Python3




# 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 =' ')

Output:

g e e k s f o r

Example #5: Iterate characters using itertools

Alternatively, you can use the islice() function from itertools to iterate over the characters of a string. islice() returns an iterator that returns selected elements from the input iterator, allowing you to specify the start and end indices of the elements you want to iterate over. Here’s an example of how you can use islice() to iterate over the characters of a string:

Python3




import itertools
 
string = "hello"
 
# Create an iterator that returns the characters from index 1 to the end of the string
char_iter = itertools.islice(string, 0, None)
 
# Iterate over the selected characters
for char in char_iter:
    print(char)
 
#This code is contributed by Edula Vinay Kumar Reddy

Output

h
e
l
l
o

Time complexity: O(n)

Space complexity: O(n)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!