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
0and the last has indexn-1(n = length of the string); negative indices run from-1(rightmost) to-n(leftmost). An out-of-range index raisesIndexError; a non-integer index raisesTypeError. - 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]raisesTypeError. - 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
inreturnsTrueif the first string appears as a substring of the second;not inreturns the opposite. - Slicing retrieves a portion of a string via an index range:
s[n:m]returns the characters from indexn(inclusive) tom(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
forloop (automatic) or awhileloop (explicit index running from0tolen(s)-1). …