You are previewing Think Python.

Think Python

Cover of Think Python by Allen B. Downey Published by O'Reilly Media, Inc.
  1. Think Python
  2. SPECIAL OFFER: Upgrade this ebook with O’Reilly
  3. Preface
    1. The Strange History of This Book
    2. Acknowledgments
    3. Contributor List
  4. 1. The Way of the Program
    1. The Python Programming Language
    2. What Is a Program?
    3. What Is Debugging?
    4. Syntax Errors
    5. Runtime Errors
    6. Semantic Errors
    7. Experimental Debugging
    8. Formal and Natural Languages
    9. The First Program
    10. Debugging
    11. Glossary
    12. Exercises
  5. 2. Variables, Expressions, and Statements
    1. Values and Types
    2. Variables
    3. Variable Names and Keywords
    4. Operators and Operands
    5. Expressions and Statements
    6. Interactive Mode and Script Mode
    7. Order of Operations
    8. String Operations
    9. Comments
    10. Debugging
    11. Glossary
    12. Exercises
  6. 3. Functions
    1. Function Calls
    2. Type Conversion Functions
    3. Math Functions
    4. Composition
    5. Adding New Functions
    6. Definitions and Uses
    7. Flow of Execution
    8. Parameters and Arguments
    9. Variables and Parameters Are Local
    10. Stack Diagrams
    11. Fruitful Functions and Void Functions
    12. Why Functions?
    13. Importing with from
    14. Debugging
    15. Glossary
    16. Exercises
  7. 4. Case Study: Interface Design
    1. TurtleWorld
    2. Simple Repetition
    3. Exercises
    4. Encapsulation
    5. Generalization
    6. Interface Design
    7. Refactoring
    8. A Development Plan
    9. Docstring
    10. Debugging
    11. Glossary
    12. Exercises
  8. 5. Conditionals and Recursion
    1. Modulus Operator
    2. Boolean Expressions
    3. Logical Operators
    4. Conditional Execution
    5. Alternative Execution
    6. Chained Conditionals
    7. Nested Conditionals
    8. Recursion
    9. Stack Diagrams for Recursive Functions
    10. Infinite Recursion
    11. Keyboard Input
    12. Debugging
    13. Glossary
    14. Exercises
  9. 6. Fruitful Functions
    1. Return Values
    2. Incremental Development
    3. Composition
    4. Boolean Functions
    5. More Recursion
    6. Leap of Faith
    7. One More Example
    8. Checking Types
    9. Debugging
    10. Glossary
    11. Exercises
  10. 7. Iteration
    1. Multiple Assignment
    2. Updating Variables
    3. The while Statement
    4. break
    5. Square Roots
    6. Algorithms
    7. Debugging
    8. Glossary
    9. Exercises
  11. 8. Strings
    1. A String Is a Sequence
    2. len
    3. Traversal with a for Loop
    4. String Slices
    5. Strings Are Immutable
    6. Searching
    7. Looping and Counting
    8. String Methods
    9. The in Operator
    10. String Comparison
    11. Debugging
    12. Glossary
    13. Exercises
  12. 9. Case Study: Word Play
    1. Reading Word Lists
    2. Exercises
    3. Search
    4. Looping with Indices
    5. Debugging
    6. Glossary
    7. Exercises
  13. 10. Lists
    1. A List Is a Sequence
    2. Lists Are Mutable
    3. Traversing a List
    4. List Operations
    5. List Slices
    6. List Methods
    7. Map, Filter, and Reduce
    8. Deleting Elements
    9. Lists and Strings
    10. Objects and Values
    11. Aliasing
    12. List Arguments
    13. Debugging
    14. Glossary
    15. Exercises
  14. 11. Dictionaries
    1. Dictionary as a Set of Counters
    2. Looping and Dictionaries
    3. Reverse Lookup
    4. Dictionaries and Lists
    5. Memos
    6. Global Variables
    7. Long Integers
    8. Debugging
    9. Glossary
    10. Exercises
  15. 12. Tuples
    1. Tuples Are Immutable
    2. Tuple Assignment
    3. Tuples as Return Values
    4. Variable-Length Argument Tuples
    5. Lists and Tuples
    6. Dictionaries and Tuples
    7. Comparing Tuples
    8. Sequences of Sequences
    9. Debugging
    10. Glossary
    11. Exercises
  16. 13. Case Study: Data Structure Selection
    1. Word Frequency Analysis
    2. Random Numbers
    3. Word Histogram
    4. Most Common Words
    5. Optional Parameters
    6. Dictionary Subtraction
    7. Random Words
    8. Markov Analysis
    9. Data Structures
    10. Debugging
    11. Glossary
    12. Exercises
  17. 14. Files
    1. Persistence
    2. Reading and Writing
    3. Format Operator
    4. Filenames and Paths
    5. Catching Exceptions
    6. Databases
    7. Pickling
    8. Pipes
    9. Writing Modules
    10. Debugging
    11. Glossary
    12. Exercises
  18. 15. Classes and Objects
    1. User-Defined Types
    2. Attributes
    3. Rectangles
    4. Instances as Return Values
    5. Objects Are Mutable
    6. Copying
    7. Debugging
    8. Glossary
    9. Exercises
  19. 16. Classes and Functions
    1. Time
    2. Pure Functions
    3. Modifiers
    4. Prototyping Versus Planning
    5. Debugging
    6. Glossary
    7. Exercises
  20. 17. Classes and Methods
    1. Object-Oriented Features
    2. Printing Objects
    3. Another Example
    4. A More Complicated Example
    5. The init Method
    6. The __str__ Method
    7. Operator Overloading
    8. Type-Based Dispatch
    9. Polymorphism
    10. Debugging
    11. Interface and Implementation
    12. Glossary
    13. Exercises
  21. 18. Inheritance
    1. Card Objects
    2. Class Attributes
    3. Comparing Cards
    4. Decks
    5. Printing the Deck
    6. Add, Remove, Shuffle, and Sort
    7. Inheritance
    8. Class Diagrams
    9. Debugging
    10. Data Encapsulation
    11. Glossary
    12. Exercises
  22. 19. Case Study: Tkinter
    1. GUI
    2. Buttons and Callbacks
    3. Canvas Widgets
    4. Coordinate Sequences
    5. More Widgets
    6. Packing Widgets
    7. Menus and Callables
    8. Binding
    9. Debugging
    10. Glossary
    11. Exercises
  23. A. Debugging
    1. Syntax Errors
      1. I Keep Making Changes and It Makes No Difference
    2. Runtime Errors
      1. My Program Does Absolutely Nothing
      2. My Program Hangs
      3. When I Run the Program, I Get an Exception
      4. I Added So Many Print Statements I Get Inundated with Output
    3. Semantic Errors
      1. My Program Doesn’t Work
      2. I’ve Got a Big Hairy Expression and It Doesn’t Do What I Expect
      3. I’ve Got a Function or Method That Doesn’t Return What I Expect
      4. I’m Really, Really Stuck and I Need Help
      5. No, I Really Need Help
  24. B. Analysis of Algorithms
    1. Order of Growth
    2. Analysis of Basic Python Operations
    3. Analysis of Search Algorithms
    4. Hashtables
  25. C. Lumpy
    1. State Diagram
    2. Stack Diagram
    3. Object Diagrams
    4. Function and Class Objects
    5. Class Diagrams
  26. Index
  27. About the Author
  28. Colophon
  29. SPECIAL OFFER: Upgrade this ebook with O’Reilly
  30. Copyright
O'Reilly logo

Chapter 8. Strings

A String Is a Sequence

A string is a sequence of characters. 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. The index indicates which character in the sequence you want (hence the name).

But you might not get what you expect:

>>> print letter
a

For most people, the first letter of 'banana' is b, not a. But for computer scientists, the index is an offset from the beginning of the string, and the offset of the first letter is zero.

>>> letter = fruit[0]
>>> print letter
b

So b is the 0th letter (“zero-eth”) of 'banana', a is the 1th letter (“one-eth”), and n is the 2th (“two-eth”) letter.

You can use any expression, including variables and operators, as an index, but the value of the index has to be an integer. Otherwise you get:

>>> letter = fruit[1.5]
TypeError: string indices must be integers

len

len is a built-in function that returns the number of characters in a string:

>>> fruit = 'banana'
>>> len(fruit)
6

To get the last letter of a string, you might be tempted to try something like this:

>>> length = len(fruit)
>>> last = fruit[length]
IndexError: string index out of range

The reason for the IndexError is that there is no letter in ’banana’ with the index 6. Since we started counting at zero, the six letters are numbered 0 to 5. To get the last character, you have to subtract ...

The best content for your career. Discover unlimited learning on demand for around $1/day.