1 Matching Annotations
  1. Sep 2020
    1. *A string is a sequence , which means it is an ordered collection of other values.

      • You can access the characters one at a time with the bracket operator:
               fruit            =
        

        ' banana ' letter = fruit[1] The second statement selects character number 1 from fruit and assigns it to letter . The expression in brackets is called an index .A lot of computations involve processing a string one character at a time. Often they start at the beginning, select each character in turn, do something to it, and continue until the end. This pattern of processing is called a traversal A segment of a string is called a slice . Selecting a slice is similar to selecting a character: s = ' Monty Python ' s[0:5] ' Monty ' s[6:12] ' PythonIt is tempting to use the [] operator on the left side of an assignment, with the intention of changing a character in a string. For example: greeting = ' Hello, world! ' greeting[0] = ' J ' TypeError: ' str ' object does not support item assignment The “object” in this case is the string and the “item” is the character you tried to assign. For now, an object is the same thing as a value, but we will refine that definition later (Section 10.10). The reason for the error is that strings are immutable ,