6.5. Loop Through a String¶
range command assigns the loop variable a new integer value each time
the loop repeats. What if we want to assign the variable something other than
6.5.1. Characters Instead of Integers¶
Recall that a string is a series of characters enclosed in quotes, like
'Hello, World!' or
"Python". Just like
range assigns a new integer
to the loop variable, we can set up a
for loop to assign different
characters from a string.
Run the following program to see how this works:
Some points to notice:
- In the
forstatement, a string (or a variable containing a string) replaces
- The first time the loop runs, the loop variable gets assigned the first
character in the string (
character = 'H'or
char = 'T').
- Each time the loop repeats, the variable holds the next character in the string.
range(n), which does NOT assign the value of
nto the loop variable, the last character in the string IS used.
- Once Python reaches the end of the string, the loop ends.
6.5.2. Characters Another Way¶
Take a look at the following code and its output:
1 2 3 4 5 6
word = 'Python' print(word) print(word) print(word) print(word)
Python P y n
Notice how lines 4 - 6 each print a single character from the string.
print(word) displays only the first letter (
the second character, and
word prints the last.
We will explore strings in more detail in a later chapter. For now, we just need to recognize that every character in a string has an index. An index is a number that tells us the location of a character in the string.
range, the index values of a string start counting at
Indexes provide a different way to loop through a string:
Some items to note:
- By using
indexvariable takes values from 0 - 5.
word[index]refers to the character in the string at position
- As written, the loop only displays characters up to index 5.
- Try replacing the string with a longer one.
- If we replace the string with a shorter one, we get an error! For
wordto work, there must be a character at index 5.
- To prevent “index out of range” errors in this loop, we should NOT use
a specific number inside
len(word)always returns the length of the current string, so changing that string will not break the loop.
6.5.3. Check Your Understanding¶
phrase = 'Code for fun', then
phrase evaluates to:
What will be printed in the THIRD iteration of the loop:
for char in 'ABCDEFGHIJ': print(char)