Iterate over characters of a string in Python
Last Updated :
22 Apr, 2023
In Python, while operating with String, one can do multiple operations on it. Let’s see how to iterate over the characters of a string in Python.
Example #1: Using simple iteration and range()
Python3
string_name = "geeksforgeeks"
for element in string_name:
print (element, end = ' ' )
print ("\n")
string_name = "GEEKS"
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
Code #1
- Time complexity: O(n), where n is the length of the string.
- Auxiliary space: O(1)
Code #2
- Time complexity: O(n), where n is the length of the string.
- Auxiliary space: O(1),
Example #2: Using enumerate() function
Python3
string_name = "Geeks"
for i, v in enumerate (string_name):
print (v)
|
Time complexity: O(n) where n is the length of the string
Auxiliary space: O(1).
Example #3: Iterate characters in reverse order
Python3
string_name = "GEEKS"
for element in string_name[ : : - 1 ]:
print (element, end = ' ' )
print ( '\n' )
string_name = "geeksforgeeks"
ran = len (string_name)
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
string_name = "geeksforgeeks"
for element in string_name[ 0 : 8 : 1 ]:
print (element, end = ' ' )
|
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"
char_iter = itertools.islice(string, 0 , None )
for char in char_iter:
print (char)
|
Time complexity: O(n)
Auxiliary Space: O(n)
Example #6: Using map() function
Approach:
- Initialize string.
- define a function that will print each character of the string in iteration.
- Using map function on a string.
- Since the map function applied function to each item in iterable in the loop and returns a new iterator that yields transformed on demand.
Python
string_name = "geeks"
def h(x):
print (x)
k = map (h, string_name)
for _ in k:
pass
|
Time Complexity: O(N). Here N is the length of the string.
Auxiliary Space: O(1). Since no extra space is required.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...