String Operations and Traversal

45 min read Strings

This is a free course. Log in to run the code exercises and track your progress.

String Operations and Traversal

A string is an immutable sequence of characters. The string operations are:

  • Concatenation +: "Class" + "XI" → "ClassXI".
  • Repetition *: "ab" * 3 → "ababab".
  • Membership in / not in: "put" in "computer" → True.
  • Slicing s[start:stop:step]: "computer"[0:4] → "comp", s[::-1] reverses.

Traversal visits each character, either directly or by index:

s = "level"
for ch in s:
    print(ch, end=" ")    # l e v e l
print()
for i in range(len(s)):
    print(i, s[i])        # index and character

A string is a palindrome if it equals its reverse. Without slicing, compare s[i] with s[len(s) - 1 - i] for the first half of the indexes.

Python exercise

Read a string and a character on two lines. Print how many times the character occurs, by traversing the string with a loop (not with count()).

s = input()
ch = input()
n = 0
for c in s:
    pass  # compare c with ch
print(n)

Log in to edit and run this code.