Iterate Strings in Python: Different ways with Examples – My programming school


iterate strings

In this tutorial, you will find out different ways to iterate strings in Python. You could use a for loop, range in Python, slicing operator, and a few more methods to traverse the characters in a string.

Multiple Ways to Iterate Strings in Python

The following are various ways to iterate the chars in a Python string. Let’s first begin with the for loop method.

Using for loop to traverse a string

It is the most prominent and straightforward technique to iterate strings. Follow the below sample code:

"""
Python Program:
 Using for loop to iterate over a string in Python
"""
string_to_iterate = "Data Science"
for char in string_to_iterate:
   print(char)

The result of the above coding snippet is as follows:

D
a
t
a

S
c
i
e
n
c
e

Python range to iterate over a string

Another quite simple way to traverse the string is by using Python range function. This method lets us access string elements using the index.

Go through the sample code given below:

"""
Python Program:
 Using range() to iterate over a string in Python
"""
string_to_iterate = "Data Science"
for char_index in range(len(string_to_iterate)):
   print(string_to_iterate[char_index])

The result of the above coding snippet is as follows:

D
a
t
a

S
c
i
e
n
c
e

Slice operator to iterate strings partially

You can traverse a string as a substring by using the Python slice operator ([]). It cuts off a substring from the original string and thus allows to iterate over it partially.

The [] operator has the following syntax:

# Slicing Operator
string [starting index : ending index : step value]

To use this method, provide the starting and ending indices along with a step value and then traverse the string. Below is the example code that iterates over the first six letters of a string.

"""
Python Program:
 Using slice [] operator to iterate over a string partially
"""
string_to_iterate = "Python Data Science"
for char in string_to_iterate[0 : 6 : 1]:
   print(char)

The result of the above coding snippet is as follows:

P
y
t
h
o
n

You can take the slice operator usage further by using it to iterate over a string but leaving every alternate character. Check out the below example:

"""
Python Program:
 Using slice [] operator to iterate over a specific parts of a string
"""
string_to_iterate = "Python_Data_Science"
for char in string_to_iterate[ :  : 2]:
   print(char)

The result of the above coding snippet is as follows:

P
t
o
_
a
a
S
i
n
e

Traverse string backward using slice operator

If you pass a -ve step value and skipping the starting as well as ending indices, then you can iterate in the backward direction. Go through the given code sample.

"""
Python Program:
 Using slice [] operator to iterate strings backward
"""
string_to_iterate = "Machine Learning"
for char in string_to_iterate[ :  : -1]:
   print(char)

The result of the above coding snippet is as follows:

g
n
i
n
r
a
e
L

e
n
i
h
c
a
M

Using indexing to iterate strings backward

Slice operator first generates a reversed string, and then we use the for loop to traverse it. Instead of doing it, we can use the indexing to iterate strings backward.

"""
Python Program:
 Using indexing to iterate strings backward
"""
string_to_iterate = "Machine Learning"
char_index = len(string_to_iterate) - 1
while char_index >= 0:
   print(string_to_iterate[char_index])
   char_index -= 1

The result of the above coding snippet is as follows:

g
n
i
n
r
a
e
L

e
n
i
h
c
a
M

Alternatively, we can pass -ve index value and traverse the string backward. See the below example.

"""
Python Program:
 Using -ve index to iterate strings backward
"""
string_to_iterate = "Learn Python"
char_index = 1
while char_index <= len(string_to_iterate):
   print(string_to_iterate[-char_index])
   char_index += 1

The result of the above coding snippet is as follows:

n
o
h
t
y
P

n
r
a
e
L

Summary – Program to iterate strings char by char

Let’s now consolidate all examples inside the Main() function and execute from there.

"""
Program:
 Python Program to iterate strings char by char
"""
def Main():
   string_to_iterate = "Data Science"
   for char in string_to_iterate:
      print(char)

   string_to_iterate = "Data Science"
   for char_index in range(len(string_to_iterate)):
      print(string_to_iterate[char_index])
      
   string_to_iterate = "Python Data Science"
   for char in string_to_iterate[0 : 6 : 1]:
      print(char)
      
   string_to_iterate = "Python_Data_Science"
   for char in string_to_iterate[ :  : 2]:
      print(char)

   string_to_iterate = "Machine Learning"
   for char in string_to_iterate[ :  : -1]:
      print(char)

   string_to_iterate = "Machine Learning"
   char_index = len(string_to_iterate) - 1
   while char_index >= 0:
      print(string_to_iterate[char_index])
      char_index -= 1

   string_to_iterate = "Learn Python"
   char_index = 1
   while char_index <= len(string_to_iterate):
      print(string_to_iterate[-char_index])
      char_index += 1

if __name__ == "__main__":
    Main()

The result of the above coding snippet is as follows:

D
a
t
a
 
S
c
i
e
n
c
e
D
a
t
a
 
S
c
i
e
n
c
e
P
y
t
h
o
n
P
t
o
_
a
a
S
i
n
e
g
n
i
n
r
a
e
L
 
e
n
i
h
c
a
M
g
n
i
n
r
a
e
L
 
e
n
i
h
c
a
M
n
o
h
t
y
P
 
n
r
a
e
L

Python  Recommended Post:


Source link

Have any Question or Comment?

Leave a Reply

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

Categories

You have successfully subscribed to myprogrammingschool

There was an error while trying to send your request. Please try again.

My Programming School will use the information you provide on this form to be in touch with you and to provide updates and marketing.