Iterating over the characters in a string: BEHIND THE SCENES!


Welcome!

Hi! Welcome to this short tutorial! We will discuss how to iterate over the character in a string, a very important concept for the course and you Computer Science journey.

Syntax

On the diagram below you can see the general syntax for iterating over the items contained in an iterable (strings are iterables and their “items” are the individual characters they contain)



Ready? Set! Go!

Once we start out for loop, the variable we’ve defined to be used in the for loop (in this case, char) will be updated on each iteration (see code in the "output" column on the diagram below).
What does this mean?
  • When the loop is run first time, char’s value will be H.
  • When the loop runs for the second time, char’s value will be e
And so on! The loop will run as many times as the number of characters in the string and the variable char will update its value wherever you’ve used it inside the loop.
In this case, we’ve printed its value. As you can see, it first prints H, then e and so on until it prints every character in the string, one at a time.



I hope it helps!
If you have any questions, please do not hesitate to ask : ) Community TAs and you classmates will always be on the forums to help you.
Estefania.

Comments

  1. Hello, would you please show how you assigned char as the variable that will be used in the loop?

    ReplyDelete
    Replies
    1. Hi, on the last example, 'char' is the variable used in the loop because of this line of code included in the "output" column:

      for char in s:

      The variable used after `for` will be the variable updated on every loop iteration.

      Delete

Post a Comment