There are multiple methods that can be used to iterate over the characters of a Python String. We are explaining them one by one below.
Python has a lot of different ways to loop through data structures like strings. The most common way to loop through a string is using a For loop. This loop will go through each character in the string and print it out.
# create a string
my_str = "devsheet"
# loop thorough string using Python For loop
for char in my_str:
print(char)
Output
d
e
v
s
h
e
e
t
The above code example loops through the string "devsheet" character by character and prints each character to the console.
The range() function is a built-in function in Python that allows you to create a sequence of numbers. In the below code example, we will learn how to use the range() function to iterate over characters of a string.
We will also be using the Python len() function to get the length of the string.
# create a string
my_str = "devsheet"
# loop through a string using range() function
for char_index in range(0, len(my_str)):
print(my_str[char_index])
Output
d
e
v
s
h
e
e
t
Explanation of the above code:
A while loop in Python will iterate over a given sequence of elements until a given condition is met. In this case, we will loop through a string until the given condition is met.
Code example
# create a string
my_str = "devsheet"
print("String is: ", my_str)
# loop through a string using while loop
i = 0
while i < len(my_str):
print(my_str[i])
i += 1
Output
String is: devsheet
d
e
v
s
h
e
e
t
The code above creates a string called "my_str" and prints it to the console. It then loops through the string using a while loop and prints each character to the console on a new line.
In Python, the enumerate() function is used to loop through a string. This function returns a tuple containing the index and value of the string. The index starts from 0.
If you want to get the index of the character along with the character in each iteration then you can use this method.
Code example
str_word = "Data"
# Iterate over the string
for i, val in enumerate(str_word):
print("Index is: {}. Value is: {}".format(i, val))
Output
Index is: 0. Value is: D
Index is: 1. Value is: a
Index is: 2. Value is: t
Index is: 3. Value is: a
This code example shows how to iterate over a string using the enumerate function. The enumerate function returns a tuple containing the index and value of each character in the string. The code example prints the index and value of each character in the string.
0 Comments