Open In App

Iterate over characters of a string in Python

Last Updated : 22 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# 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

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




# 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

Time complexity: O(n) where n is the length of the string

Auxiliary space: O(1).

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




# Python program to iterate over character
# of string in python
 
string_name = "geeks"
 
def h(x):
    print(x)
 
# Using map function
k = map(h, string_name)
 
for _ in k:
    pass


Output

g
e
e
k
s

Time Complexity: O(N). Here N is the length of the string. 
Auxiliary Space: O(1). Since no extra space is required. 



Previous Article
Next Article

Similar Reads

Iterate over words of a String in Python
Given a String comprising of many words separated by space, write a Python program to iterate over these words of the string. Examples: Input: str = "GeeksforGeeks is a computer science portal for Geeks" Output: GeeksforGeeks is a computer science portal for Geeks Input: str = "Geeks for Geeks" Output: Geeks for Geeks Method 1: Using split() Using
4 min read
Python | Iterate over multiple lists simultaneously
Iterating over single lists, refers to using for loops for iteration over a single element of a single list at a particular step whereas in iterating over multiple lists simultaneously, we refer using for loops for iteration over a single element of multiple lists at a particular step. Iterate over multiple lists at a time For better understanding
4 min read
Iterate over a set in Python
In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements.There are numerous ways that can be used to iterate over a Set. Some of these ways provide faster time execution as compared to others. Some of these ways include, iterating using for/while loops, comprehensions, iterators and their variat
6 min read
Python - Iterate over Columns in NumPy
Numpy (abbreviation for 'Numerical Python') is a library for performing large-scale mathematical operations in a fast and efficient manner. This article serves to educate you about methods one could use to iterate over columns in an 2D NumPy array. Since a single-dimensional array only consists of linear elements, there doesn't exists a distinguish
3 min read
How to Iterate over Dataframe Groups in Python-Pandas?
In this article, we'll see how we can iterate over the groups in which a data frame is divided. So, let's see different ways to do this task. First, Let's create a data frame: C/C++ Code # import pandas library import pandas as pd # dictionary dict = {'X': ['A', 'B', 'A', 'B'], 'Y': [1, 4, 3, 2]} # create a dataframe df = pd.DataFrame(dict) # show
2 min read
How to iterate over OrderedDict in Python?
An OrderedDict is a subclass that preserves the order in which the keys are inserted. The difference between OrderedDict and Dict is that the normal Dict does not keep a track of the way the elements are inserted whereas the OrderedDict remembers the order in which the elements are inserted. Explanation: Input : original_dict = { 'a':1, 'b':2, 'c':
2 min read
How to iterate over files in directory using Python?
Directory also sometimes known as a folder are unit organizational structure in a system’s file system for storing and locating files or more folders. Python as a scripting language provides various methods to iterate over files in a directory. Below are the various approaches by using which one can iterate over files in a directory using python: M
2 min read
Python - How to Iterate over nested dictionary ?
In this article, we will discuss how to iterate over a nested dictionary in Python. Nested dictionary means dictionary inside a dictionary and we are going to see every possible way of iterating over such a data structure. Nested dictionary in use: {'Student 1': {'Name': 'Bobby', 'Id': 1, 'Age': 20}, 'Student 2': {'Name': 'ojaswi', 'Id': 2, 'Age':
3 min read
Python - Iterate over Tuples in Dictionary
In this article, we will discuss how to Iterate over Tuples in Dictionary in Python. Method 1: Using index We can get the particular tuples by using an index: Syntax: dictionary_name[index] To iterate the entire tuple values in a particular index for i in range(0, len(dictionary_name[index])): print(dictionary_name[index][i] Example: Python Code #
2 min read
How to Iterate over months between two dates in Python?
In this article, we will discuss how to iterate over months between two dates using Python. We can iterate over months between two dates using timedelta and rrule methods. Method 1: Iteration using timedeltatimedelta() is used for calculating differences in dates and also can be used for date manipulations in Python Example: But using timedelta we
2 min read