Skip to content

Computer Science · Ch 8 — Strings

Summary

Summary

  • A string is a sequence of Unicode characters enclosed in single, double or triple quotes; triple-quoted strings may span multiple lines.
  • Indexing with square brackets accesses individual characters. The first character has index 0 and the last has index n-1 (n = length of the string); negative indices run from -1 (rightmost) to -n (leftmost). An out-of-range index raises IndexError; a non-integer index raises TypeError.
  • The built-in function len() returns the length of a string.
  • Strings are immutable — a string cannot be changed after it is created; assigning to s[i] raises TypeError.
  • Concatenation joins two strings with the + operator; repetition with * produces a string repeated a given number of times. Neither modifies the original strings.
  • The membership operator in returns True if the first string appears as a substring of the second; not in returns the opposite.
  • Slicing retrieves a portion of a string via an index range: s[n:m] returns the characters from index n (inclusive) to m (exclusive). Missing indices default to the start/end; a third index gives the step size; s[::-1] returns the string reversed.
  • A string can be traversed character by character with a for loop (automatic) or a while loop (explicit index running from 0 to len(s)-1). …