12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Sequence OperationsAs sequences, strings support operations that assume a positional ordering amongitems. For example, if we have a four-character string, we can verify its length withthe built-in len function and fetch its components with indexing expressions:>>> S = 'Spam'>>> len(S) # Length4>>> S[0] # The first item in S, indexing by zero-based position'S'>>> S[1] # The second item from the left'p'In <strong>Python</strong>, indexes are coded as offsets from the front, and so start from 0: the firstitem is at index 0, the second is at index 1, and so on. In <strong>Python</strong>, we can also indexbackward, from the end:>>> S[-1] # The last item from the end in S'm'>>> S[-2] # The second to last item from the end'a'Formally, a negative index is simply added to the string’s size, so the following twooperations are equivalent (though the first is easier to code and less easy to getwrong):>>> S[-1] # The last item in S'm'>>> S[len(S)-1] # Negative indexing, the hard way'm'Notice that we can use an arbitrary expression in the square brackets, not just ahardcoded number literal—anywhere that <strong>Python</strong> expects a value, we can use a literal,a variable, or any expression. <strong>Python</strong>’s syntax is completely general this way.In addition to simple positional indexing, sequences also support a more generalform of indexing known as slicing, which is a way to extract an entire section (slice)in a single step. For example:>>> S # A 4-character string'Spam'>>> S[1:3] # Slice of S from offsets 1 through 2 (not 3)'pa'Probably the easiest way to think of slices is that they are a way to extract an entirecolumn from a string in a single step. Their general form, X[I:J], means “give meeverything in X from offset I up to but not including offset J.” The result is returnedin a new object. The last operation above, for instance, gives us all the characters instring S from offsets 1 through 2 (that is, 3–1) as a new string. The effect is to slice or“parse out” the two characters in the middle.70 | Chapter 4: Introducing <strong>Python</strong> Object Types

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!