
Syntax: String Loops
Iterating over the characters in a string with string loops.
Loops Through Characters of a String
In Python, for loops can iterate directly over all the characters of a string.
for character in "Hello there!":
print(character)
> "H"
> "e"
> "l"
> "l"
> "o"
> " "
> "t"
> "h"
> "e"
> "r"
> "e"
> "!"
message = "I am Bob"
compressed_message = ""
for character in message:
if character.isalpha():
compressed_message = compressed_message + character.lower()
print(compressed_message)
> "iambob"
There are a couple things to point out in the second example above:
- Loops and conditionals can be nested inside each other by adding an extra layer of indentation.
- Another string can be extended by repeatedly concatenating strings and re-assigning the result back to it.
Practice: Count Number of Vowels
-
Create a string variable named
my_stringand assign it the value"Hello, World!". -
Create a variable
vowelsand assign it the string of vowels"aeiou". -
Create a variable
countand initialize it to0. -
Write a
forloop to iterate over each character inmy_string. -
Inside the loop, use an
ifstatement to check if the lower case version of the character is in vowels. -
If it is, increment
countby1. -
After the loop, print
count.
Run your code and confirm that the output is 3 (the number of vowels in "Hello, World!").
HINT*: Click here for a hint
> 3
SOLUTION*: Click here for an example solution
my_string = "Hello, World!"
vowels = "aeiou"
count = 0
for character in my_string:
if character.lower() in vowels:
count += 1
print(count)
Practice: Reverse a String
-
Create a string variable named
my_stringand assign it the value"Python". -
Create a new empty string variable named
reversed_string. -
Write a
forloop to iterate over each character inmy_string. -
Inside the loop, prepend each character to
reversed_string. -
After the loop, print
reversed_string.
Run your code and confirm that the output is "nohtyP".
HINT*: Click here for a hint
> "nohtyP"
SOLUTION*: Click here for an example solution
my_string = "Python"
reversed_string = ""
for character in my_string:
reversed_string = character + reversed_string
print(reversed_string)
Great work so far! Completing these challenges successfully shows your understanding of loops and strings in Python.