6. For over a string

A string is iterable: a for loop visits it one character at a time, from left to right.

  • char is a name you choose; each pass it holds one character, which is itself a string of length one.
  • Spaces and punctuation are characters too, so they also get a pass.
  • Use a different name for the loop variable than for the original string to keep the code clear.
#01

Print every character

Loop over the string "code" and print each character, one per line.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Format each character

Loop over the string "abc" and print each character followed by - using an f-string.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Uppercase each character

Loop over the string "hey" and print the uppercase version of each character with .upper().

Print exactly:

Create a free account to save your progress and unlock chapter 2.