dcsimg
 

How to Iterate or Loop Through Strings in Python using For Loop

Friday May 7th 2021 by James Payne
Article Image

This Python programming cheat sheet shows you how to iterate and loop through a string using the Python For loop. Try it out. 

One pivotal operation you can perform on a string of characters in Python is to iterate through the string. There are several methods to perform this action. For starters, we could use the for</> loop and in operator, as in the example below:

# Python code snippet to iterate through the characters in a string
# and print them out.

# Assign value to our string variable
string_superhero = "ConfusedMan"

# Create or iterator loop using the for loop
for element in string_superhero:
    print(element, end =".")

The above code will result the following prinout:

C.o.n.f.u.s.e.d.M.a.n.

We could also have our characters in the string print out on each line instead of on a single line.Try out this Python code:

# Python code snippet to iterate through the characters in a string
# and print them out.

# Assign value to our string variables
string_superhero = "ConfusedMan!"
string_herosong = "Nanananananana"

print("Who will save the day now?")
print("From a great distance you see...")

# Create or iterator loop using the for loop
for element in string_herosong:
    print(element, end ="\n") # separate characters onto a separate line
                             # from supersong

print(string_superhero)
print("Confsed Man asks: 'Where am I?'")

This would result in the ridiculous print out:

Who will save the day now?
From a great distance you see...
N
a
n
a
n
a
n
a
n
a
n
a
n
a
ConfusedMan!
Confsed Man asks: 'Where am I?'

Of course, we could also achieve the same effect by replacing the newline escape character (“\n”) portion of the code and just tell Python to print each element instead, as we do in this Python code snippet:

# Python code snippet to iterate through the characters in a string
# and print them out.

# Assign value to our string variables
string_superhero = "ConfusedMan!"
string_herosong = "Nanananananana"

print("Who will save the day now?")
print("From a great distance you see...")

# Create or iterator loop using the for loop
for element in string_herosong:
    print(element) # prints each element (character) of the string
                             # on a separate line

print(string_superhero)
print("Confsed Man asks: 'Where am I?'")

This would give us the same results as the previous example.

Home
Mobile Site | Full Site