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.

In a slice, the left bound defaults to zero, and the right bound defaults to the lengthof the sequence being sliced. This leads to some common usage variations:>>> S[1:] # Everything past the first (1:len(S))'pam'>>> S # S itself hasn't changed'Spam'>>> S[0:3] # Everything but the last'Spa'>>> S[:3] # Same as S[0:3]'Spa'>>> S[:-1] # Everything but the last again, but simpler (0:-1)'Spa'>>> S[:] # All of S as a top-level copy (0:len(S))'Spam'Note how negative offsets can be used to give bounds for slices, too, and how the lastoperation effectively copies the entire string. As you’ll learn later, there is no reasonto copy a string, but this form can be useful for sequences like lists.Finally, as sequences, strings also support concatenation with the plus sign (joiningtwo strings into a new string), and repetition (making a new string by repeatinganother):>>> S'Spam'>>> S + 'xyz' # Concatenation'Spamxyz'>>> S # S is unchanged'Spam'>>> S * 8 # Repetition'SpamSpamSpamSpamSpamSpamSpamSpam'Notice that the plus sign (+) means different things for different objects: addition fornumbers, and concatenation for strings. This is a general property of <strong>Python</strong> thatwe’ll call polymorphism later in the book—in sum, the meaning of an operationdepends on the objects being operated on. As you’ll see when we study dynamictyping, this polymorphism property accounts for much of the conciseness and flexibilityof <strong>Python</strong> code. Because types aren’t constrained, a <strong>Python</strong>-coded operationcan normally work on many different types of objects automatically, as long as theysupport a compatible interface (like the + operation here). This turns out to be a hugeidea in <strong>Python</strong>; you’ll learn more about it later on our tour.ImmutabilityNotice that in the prior examples, we were not changing the original string with anyof the operations we ran on it. Every string operation is defined to produce a newstring as its result, because strings are immutable in <strong>Python</strong>—they cannot be changedin-place after they are created. For example, you can’t change a string by assigning toStrings | 71

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

Saved successfully!

Ooh no, something went wrong!