Test Your Knowledge: Answers

 

 
  1. No, because methods are always type-specific; that is, they only work on a single data type. Expressions like X+Y and built-in functions like len(X) are generic, though, and may work on a variety of types. In this case, for instance, the in membership expression has a similar effect as the string find, but it can be used to search both strings and lists. In Python 3.0, there is some attempt to group methods by categories (for example, the mutable sequence types list and bytearray have similar method sets), but methods are still more type-specific than other operation sets.
  2. Yes. Unlike methods, expressions are generic and apply to many types. In this case, the slice expression is really a sequence operation—it works on any type of sequence object, including strings, lists, and tuples. The only difference is that when you slice a list, you get back a new list.
  3. The built-in ord(S) function converts from a one-character string to an integer character code; chr(I) converts from the integer code back to a string.
  4. Strings cannot be changed; they are immutable. However, you can achieve a similar effect by creating a new string—by concatenating, slicing, running formatting expressions, or using a method call like replace—and then assigning the result back to the original variable name.
  5. You can slice the string using S[2:4], or split on the comma and index the string using S.split(',')[1]. Try these interactively to see for yourself.
  6. Six. The string "a\nb\x1f\000d" contains the bytes a, newline (\n), b, binary 31 (a hex escape \x1f), binary 0 (an octal escape \000), and d. Pass the string to the built-in len function to verify this, and print each of its character’s ord results to see the actual byte values. See Table 7-2 for more details.
  7. You should never use the string module instead of string object method calls today—it’s deprecated, and its calls are removed completely in Python 3.0. The only reason for using the string module at all is for its other tools, such as predefined constants. You might also see it appear in what is now very old and dusty Python code.