You are previewing Learning Python, 4th Edition.

Learning Python, 4th Edition

Cover of Learning Python, 4th Edition by Mark Lutz Published by O'Reilly Media, Inc.
  1. Learning Python
  2. Dedication
  3. A Note Regarding Supplemental Files
  4. Preface
    1. About This Fourth Edition
      1. Coverage for Both 3.0 and 2.6
      2. New Chapters
      3. Changes to Existing Material
      4. Specific Language Extensions in 2.6 and 3.0
      5. Specific Language Removals in 3.0
    2. About The Third Edition
      1. The Third Edition’s Python Language Changes
      2. The Third Edition’s Python Training Changes
      3. The Third Edition’s Structural Changes
      4. The Third Edition’s Scope Changes
    3. About This Book
      1. This Book’s Prerequisites
      2. This Book’s Scope and Other Books
      3. This Book’s Style and Structure
    4. Book Updates
    5. About the Programs in This Book
    6. Using Code Examples
    7. Font Conventions
    8. Safari® Books Online
    9. How to Contact Us
    10. Acknowledgments
  5. I. Getting Started
    1. 1. A Python Q&A Session
      1. Why Do People Use Python?
      2. Is Python a “Scripting Language”?
      3. OK, but What’s the Downside?
      4. Who Uses Python Today?
      5. What Can I Do with Python?
      6. How Is Python Supported?
      7. What Are Python’s Technical Strengths?
      8. How Does Python Stack Up to Language X?
      9. Chapter Summary
      10. Test Your Knowledge: Quiz
      11. Test Your Knowledge: Answers
    2. 2. How Python Runs Programs
      1. Introducing the Python Interpreter
      2. Program Execution
      3. Execution Model Variations
      4. Chapter Summary
      5. Test Your Knowledge: Quiz
      6. Test Your Knowledge: Answers
    3. 3. How You Run Programs
      1. The Interactive Prompt
      2. System Command Lines and Files
      3. Clicking File Icons
      4. Module Imports and Reloads
      5. Using exec to Run Module Files
      6. The IDLE User Interface
      7. Other IDEs
      8. Other Launch Options
      9. Which Option Should I Use?
      10. Chapter Summary
      11. Test Your Knowledge: Quiz
      12. Test Your Knowledge: Answers
      13. Test Your Knowledge: Part I Exercises
  6. II. Types and Operations
    1. 4. Introducing Python Object Types
      1. Why Use Built-in Types?
      2. Numbers
      3. Strings
      4. Lists
      5. Dictionaries
      6. Tuples
      7. Files
      8. Other Core Types
      9. Chapter Summary
      10. Test Your Knowledge: Quiz
      11. Test Your Knowledge: Answers
    2. 5. Numeric Types
      1. Numeric Type Basics
      2. Numbers in Action
      3. Other Numeric Types
      4. Numeric Extensions
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
    3. 6. The Dynamic Typing Interlude
      1. The Case of the Missing Declaration Statements
      2. Shared References
      3. Dynamic Typing Is Everywhere
      4. Chapter Summary
      5. Test Your Knowledge: Quiz
      6. Test Your Knowledge: Answers
    4. 7. Strings
      1. String Literals
      2. Strings in Action
      3. String Methods
      4. String Formatting Expressions
      5. String Formatting Method Calls
      6. General Type Categories
      7. Chapter Summary
      8. Test Your Knowledge: Quiz
      9. Test Your Knowledge: Answers
    5. 8. Lists and Dictionaries
      1. Lists
      2. Lists in Action
      3. Dictionaries
      4. Dictionaries in Action
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
    6. 9. Tuples, Files, and Everything Else
      1. Tuples
      2. Files
      3. Type Categories Revisited
      4. Object Flexibility
      5. References Versus Copies
      6. Comparisons, Equality, and Truth
      7. Python’s Type Hierarchies
      8. Other Types in Python
      9. Built-in Type Gotchas
      10. Chapter Summary
      11. Test Your Knowledge: Quiz
      12. Test Your Knowledge: Answers
      13. Test Your Knowledge: Part II Exercises
  7. III. Statements and Syntax
    1. 10. Introducing Python Statements
      1. Python Program Structure Revisited
      2. A Tale of Two ifs
      3. A Quick Example: Interactive Loops
      4. Chapter Summary
      5. Test Your Knowledge: Quiz
      6. Test Your Knowledge: Answers
    2. 11. Assignments, Expressions, and Prints
      1. Assignment Statements
      2. Expression Statements
      3. Print Operations
      4. Chapter Summary
      5. Test Your Knowledge: Quiz
      6. Test Your Knowledge: Answers
    3. 12. if Tests and Syntax Rules
      1. if Statements
      2. Python Syntax Rules
      3. Truth Tests
      4. The if/else Ternary Expression
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
    4. 13. while and for Loops
      1. while Loops
      2. break, continue, pass, and the Loop else
      3. for Loops
      4. Loop Coding Techniques
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
    5. 14. Iterations and Comprehensions, Part 1
      1. Iterators: A First Look
      2. List Comprehensions: A First Look
      3. Other Iteration Contexts
      4. New Iterables in Python 3.0
      5. Other Iterator Topics
      6. Chapter Summary
      7. Test Your Knowledge: Quiz
      8. Test Your Knowledge: Answers
    6. 15. The Documentation Interlude
      1. Python Documentation Sources
      2. Common Coding Gotchas
      3. Chapter Summary
      4. Test Your Knowledge: Quiz
      5. Test Your Knowledge: Answers
      6. Test Your Knowledge: Part III Exercises
  8. IV. Functions
    1. 16. Function Basics
      1. Why Use Functions?
      2. Coding Functions
      3. A First Example: Definitions and Calls
      4. A Second Example: Intersecting Sequences
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
    2. 17. Scopes
      1. Python Scope Basics
      2. The global Statement
      3. Scopes and Nested Functions
      4. The nonlocal Statement
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
    3. 18. Arguments
      1. Argument-Passing Basics
      2. Special Argument-Matching Modes
      3. The min Wakeup Call!
      4. Generalized Set Functions
      5. Emulating the Python 3.0 print Function
      6. Chapter Summary
      7. Test Your Knowledge: Quiz
      8. Test Your Knowledge: Answers
    4. 19. Advanced Function Topics
      1. Function Design Concepts
      2. Recursive Functions
      3. Function Objects: Attributes and Annotations
      4. Anonymous Functions: lambda
      5. Mapping Functions over Sequences: map
      6. Functional Programming Tools: filter and reduce
      7. Chapter Summary
      8. Test Your Knowledge: Quiz
      9. Test Your Knowledge: Answers
    5. 20. Iterations and Comprehensions, Part 2
      1. List Comprehensions Revisited: Functional Tools
      2. Iterators Revisited: Generators
      3. 3.0 Comprehension Syntax Summary
      4. Timing Iteration Alternatives
      5. Function Gotchas
      6. Chapter Summary
      7. Test Your Knowledge: Quiz
      8. Test Your Knowledge: Answers
      9. Test Your Knowledge: Part IV Exercises
  9. V. Modules
    1. 21. Modules: The Big Picture
      1. Why Use Modules?
      2. Python Program Architecture
      3. How Imports Work
      4. The Module Search Path
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
    2. 22. Module Coding Basics
      1. Module Creation
      2. Module Usage
      3. Module Namespaces
      4. Reloading Modules
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
    3. 23. Module Packages
      1. Package Import Basics
      2. Package Import Example
      3. Why Use Package Imports?
      4. Package Relative Imports
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
    4. 24. Advanced Module Topics
      1. Data Hiding in Modules
      2. Enabling Future Language Features
      3. Mixed Usage Modes: __name__ and __main__
      4. Changing the Module Search Path
      5. The as Extension for import and from
      6. Modules Are Objects: Metaprograms
      7. Importing Modules by Name String
      8. Transitive Module Reloads
      9. Module Design Concepts
      10. Module Gotchas
      11. Chapter Summary
      12. Test Your Knowledge: Quiz
      13. Test Your Knowledge: Answers
      14. Test Your Knowledge: Part V Exercises
  10. VI. Classes and OOP
    1. 25. OOP: The Big Picture
      1. Why Use Classes?
      2. OOP from 30,000 Feet
      3. Chapter Summary
      4. Test Your Knowledge: Quiz
      5. Test Your Knowledge: Answers
    2. 26. Class Coding Basics
      1. Classes Generate Multiple Instance Objects
      2. Classes Are Customized by Inheritance
      3. Classes Can Intercept Python Operators
      4. The World’s Simplest Python Class
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
    3. 27. A More Realistic Example
      1. Step 1: Making Instances
      2. Step 2: Adding Behavior Methods
      3. Step 3: Operator Overloading
      4. Step 4: Customizing Behavior by Subclassing
      5. Step 5: Customizing Constructors, Too
      6. Step 6: Using Introspection Tools
      7. Step 7 (Final): Storing Objects in a Database
      8. Future Directions
      9. Chapter Summary
      10. Test Your Knowledge: Quiz
      11. Test Your Knowledge: Answers
    4. 28. Class Coding Details
      1. The class Statement
      2. Methods
      3. Inheritance
      4. Namespaces: The Whole Story
      5. Documentation Strings Revisited
      6. Classes Versus Modules
      7. Chapter Summary
      8. Test Your Knowledge: Quiz
      9. Test Your Knowledge: Answers
    5. 29. Operator Overloading
      1. The Basics
      2. Indexing and Slicing: __getitem__ and __setitem__
      3. Index Iteration: __getitem__
      4. Iterator Objects: __iter__ and __next__
      5. Membership: __contains__, __iter__, and __getitem__
      6. Attribute Reference: __getattr__ and __setattr__
      7. String Representation: __repr__ and __str__
      8. Right-Side and In-Place Addition: __radd__ and __iadd__
      9. Call Expressions: __call__
      10. Comparisons: __lt__, __gt__, and Others
      11. Boolean Tests: __bool__ and __len__
      12. Object Destruction: __del__
      13. Chapter Summary
      14. Test Your Knowledge: Quiz
      15. Test Your Knowledge: Answers
    6. 30. Designing with Classes
      1. Python and OOP
      2. OOP and Inheritance: “Is-a” Relationships
      3. OOP and Composition: “Has-a” Relationships
      4. OOP and Delegation: “Wrapper” Objects
      5. Pseudoprivate Class Attributes
      6. Methods Are Objects: Bound or Unbound
      7. Multiple Inheritance: “Mix-in” Classes
      8. Classes Are Objects: Generic Object Factories
      9. Other Design-Related Topics
      10. Chapter Summary
      11. Test Your Knowledge: Quiz
      12. Test Your Knowledge: Answers
    7. 31. Advanced Class Topics
      1. Extending Built-in Types
      2. The “New-Style” Class Model
      3. New-Style Class Changes
      4. New-Style Class Extensions
      5. Static and Class Methods
      6. Decorators and Metaclasses: Part 1
      7. Class Gotchas
      8. Chapter Summary
      9. Test Your Knowledge: Quiz
      10. Test Your Knowledge: Answers
      11. Test Your Knowledge: Part VI Exercises
  11. VII. Exceptions and Tools
    1. 32. Exception Basics
      1. Why Use Exceptions?
      2. Exceptions: The Short Story
      3. Chapter Summary
      4. Test Your Knowledge: Quiz
      5. Test Your Knowledge: Answers
    2. 33. Exception Coding Details
      1. The try/except/else Statement
      2. The try/finally Statement
      3. Unified try/except/finally
      4. The raise Statement
      5. The assert Statement
      6. with/as Context Managers
      7. Chapter Summary
      8. Test Your Knowledge: Quiz
      9. Test Your Knowledge: Answers
    3. 34. Exception Objects
      1. Exceptions: Back to the Future
      2. Why Exception Hierarchies?
      3. Built-in Exception Classes
      4. Custom Print Displays
      5. Custom Data and Behavior
      6. Chapter Summary
      7. Test Your Knowledge: Quiz
      8. Test Your Knowledge: Answers
    4. 35. Designing with Exceptions
      1. Nesting Exception Handlers
      2. Exception Idioms
      3. Exception Design Tips and Gotchas
      4. Core Language Summary
      5. Chapter Summary
      6. Test Your Knowledge: Quiz
      7. Test Your Knowledge: Answers
      8. Test Your Knowledge: Part VII Exercises
  12. VIII. Advanced Topics
    1. 36. Unicode and Byte Strings
      1. String Changes in 3.0
      2. String Basics
      3. Python 3.0 Strings in Action
      4. Coding Unicode Strings
      5. Using 3.0 Bytes Objects
      6. Using 3.0 (and 2.6) bytearray Objects
      7. Using Text and Binary Files
      8. Using Unicode Files
      9. Other String Tool Changes in 3.0
      10. Chapter Summary
      11. Test Your Knowledge: Quiz
      12. Test Your Knowledge: Answers
    2. 37. Managed Attributes
      1. Why Manage Attributes?
      2. Properties
      3. Descriptors
      4. __getattr__ and __getattribute__
      5. Example: Attribute Validations
      6. Chapter Summary
      7. Test Your Knowledge: Quiz
    3. 38. Decorators
      1. What’s a Decorator?
      2. The Basics
      3. Coding Function Decorators
      4. Coding Class Decorators
      5. Managing Functions and Classes Directly
      6. Example: “Private” and “Public” Attributes
      7. Example: Validating Function Arguments
      8. Chapter Summary
      9. Test Your Knowledge: Quiz
      10. Test Your Knowledge: Answers
    4. 39. Metaclasses
      1. To Metaclass or Not to Metaclass
      2. The Metaclass Model
      3. Declaring Metaclasses
      4. Coding Metaclasses
      5. Example: Adding Methods to Classes
      6. Example: Applying Decorators to Methods
      7. Chapter Summary
      8. Test Your Knowledge: Quiz
      9. Test Your Knowledge: Answers
  13. IX. Appendixes
    1. A. Installation and Configuration
      1. Installing the Python Interpreter
      2. Configuring Python
      3. For More Help
    2. B. Solutions to End-of-Part Exercises
      1. Part I, Getting Started
      2. Part II, Types and Operations
      3. Part III, Statements and Syntax
      4. Part IV, Functions
      5. Part V, Modules
      6. Part VI, Classes and OOP
      7. Part VII, Exceptions and Tools
  14. Index
  15. About the Author
  16. Colophon
  17. Copyright
O'Reilly logo

Chapter 7. Strings

The next major type on our built-in object tour is the Python string—an ordered collection of characters used to store and represent text-based information. We looked briefly at strings in Chapter 4. Here, we will revisit them in more depth, filling in some of the details we skipped then.

From a functional perspective, strings can be used to represent just about anything that can be encoded as text: symbols and words (e.g., your name), contents of text files loaded into memory, Internet addresses, Python programs, and so on. They can also be used to hold the absolute binary values of bytes, and multibyte Unicode text used in internationalized programs.

You may have used strings in other languages, too. Python’s strings serve the same role as character arrays in languages such as C, but they are a somewhat higher-level tool than arrays. Unlike in C, in Python, strings come with a powerful set of processing tools. Also unlike languages such as C, Python has no distinct type for individual characters; instead, you just use one-character strings.

Strictly speaking, Python strings are categorized as immutable sequences, meaning that the characters they contain have a left-to-right positional order and that they cannot be changed in-place. In fact, strings are the first representative of the larger class of objects called sequences that we will study here. Pay special attention to the sequence operations introduced in this chapter, because they will work the same on other ...

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