Introduction
Because a string is a sequence of characters, we can loop through each character. For this, we can use any of the below approach.
for Loop
We can iterate over all the characters of the string using a for loop.
In [1]:
str = "Logical"
for i in str:
print(i)
for Loop using range() function – Loop through index numbers
We can use the index positions of the characters to loop through the string. For this, we will use the range() function to iterate through the index positions up to the length of the string.
In [1]:
str = "Logical"
for i in range(len(str)):
print(str[i])
While loop
While loop can also be used to iterate over the string.
Here, we will initialize a variable with index position 0. The loop will go up to the length of the string and on every iteration, we will increase the value of the variable by 1.
In [1]:
str = "Logical"
i = 0
while i < len(str):
print(str[i])
i = i+1