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

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

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):
    i = i + 1


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):
    idx = idx + 2

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

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.