Computer Science · Ch 8 — Strings
Traversing a String
Traversing a String
Traversing a string means visiting it character by character, from the first to the last, usually to examine or process each character in turn. Since a string is a sequence, either of Python's two loops can traverse it — the for loop and the while loop.
(A) Traversal using a for loop
The for loop is the more direct tool: it walks the string itself, handing each character to the loop variable in order. No index bookkeeping is needed — the loop starts at the first character and stops automatically after the last character has been accessed.
>>> s = 'Hello World!'
>>> for ch in s:
print(ch, end='')
Hello World!
On each pass, ch holds the next character of s. The end='' argument makes print() put nothing (instead of a newline) after each character, so the characters appear joined on one line — reproducing the original string as the output.
(B) Traversal using a while loop
The while loop traverses by explicit indexing: an index variable starts at 0, the loop body accesses s[index], and the index is incremented until it passes the last valid position. The len() function supplies the stopping point.
>>> s = 'Hello World!'
>>> index = 0
>>> while index < len(s): # len(): gives the string's length
print(s[index], end='')
index += 1
Hello World!
The loop keeps running as long as the condition index < len(s) is True, so index takes every value from 0 up to len(s) - 1 — exactly the range of valid positive indices. The moment index reaches len(s), the condition turns False and the loop ends.