How to Traverse a String in Python


In this example, we will learn how to traverse a string in Python.

1) Method 1:Traverse through for-loop which is widely used to loop through an object.

2) Method 2:Use iter() function and next() function.

The iter() function is a built-in function in Python, and it will return an iterator object. The next() function is used to move to next position in the iteration. When the iteration is completed, calling the next() function will throw a StopIteration exception.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

print('Output of method 1:')
my_str = 'I Love Basketball'
# Method 1:
for v in my_str:
    print(v)

print('\nOutput of method 2:')

# Method 2:
ite = iter(my_str)
while True:
    try:
        each = next(ite)
    except StopIteration:
        break
    print(each)

Output:

Output of method 1:
I
 
L
o
v
e
 
B
a
s
k
e
t
b
a
l
l

Output of method 2:
I
 
L
o
v
e
 
B
a
s
k
e
t
b
a
l
l
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement