Skip to content

How to traverse a string in Python using while loop | Example code

  • by

Traverse a string in Python using while loop is simple, see below code. It’s making sure that the condition is correct in every iteration.

j = 0
while j < len(string):
    j += 1
    print(string[0:j])

Example traversal through a string with a loop in Python

Simple example code. While loop will run until a condition is true, so when i is equal to the length of the string, the condition is false, and the body of the loop is not executed.

fruit = "Apple"

i = 0
while i < len(fruit):
    print(fruit[i])
    i = i + 1

Output:

How to traverse a string in Python using while loop

Find out How many times is the letter o printed by the following statements?

s = "python rocks"
idx = 1
while idx < len(s):
    print(s[idx])
    idx = idx + 2

Do comment if you have any doubts and suggestions on this Python while loop topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *