Skip to content

Python iterate string | Example code

  • by

Simply use loops like (for loop & while loop) to iterate strings 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 backward

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

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 the 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 or suggestions on this Pytho string basic 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading