LearnWave
Learn it. Master it.

Strings

Traversing a string

Print a string one character at a time.

Traversing a string means visiting each character in turn, from the first to the last. There are two ways.

With a for loop: for ch in s: print(ch, end = ''). The loop goes from the first character to the last automatically, and stops by itself.

With a while loop, using an index:

  • index = 0
  • while index < len(s): print(s[index], end = ''); index += 1

The index runs from 0 to len(s) - 1; when it reaches len(s), the condition becomes false and the loop stops.

In both, end = '' keeps all the characters on one line, with nothing between them, instead of printing each on a new line.

Traversal is the basis of many string tasks: counting a character, searching for something, or building a new string character by character, as in the programs of section 8.6.

for ch in s, or while index < len(s).

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.