Python iterate string | Example code

Simply use loops like (for loop & while loop) to iterate string in Python. In this tutorial, we will find out different ways to iterate strings in Python.

Python iterate string example

Simple example code

s = "Hello"

for ch in s:
    print(ch, "index :", s.index(ch))

Output:

Python iterate string

Iterate String with index using for loop and range()

s = "Hello"

for var in range(len(s)):
    print(s[var])

Output:

H
e
l
l
o

Iterate String with index using while loop and range()

s = "ABC"
i = 0

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

Output:

A
B
C

Iterate string backwards

Using slice notations string[start position (-) : stop position (-) : incremental step (-)] we can iterate through a portion of our string variable in backwards.

s = "ABC"
i = 0

for i in s[-1: -4: -1]:
    print(i)

Output:

C
B
A

How to iterate through characters in a string python?

Answer: You can iterate pretty much anything in python using the for loop construct,

for c in "string":
    print(c, end=',')

Output: s,t,r,i,n,g,

Using slice [] operator to iterate over a string partially

s = "ABC"
i = 0

for char in s[0: 4: 1]:
    print(char)

Output:

A
B
C

Do comment if you have any doubts and suggestions on this Pytho string basic 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.