SlideShare a Scribd company logo
Instant Ebook Access, One Click Away – Begin at ebookgate.com
Python pocket reference 5ed. Edition Mark Lutz
https://ebookgate.com/product/python-pocket-reference-5ed-
edition-mark-lutz/
OR CLICK BUTTON
DOWLOAD EBOOK
Get Instant Ebook Downloads – Browse at https://ebookgate.com
Click here to visit ebookgate.com and download ebook now
Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...
Programming Python 3rd ed Edition Mark Lutz
https://ebookgate.com/product/programming-python-3rd-ed-edition-mark-
lutz/
ebookgate.com
Learning Python 2nd ed Edition Mark Lutz
https://ebookgate.com/product/learning-python-2nd-ed-edition-mark-
lutz/
ebookgate.com
grep Pocket Reference A Quick Pocket Reference for a
Utility Every Unix User Needs Pocket Reference O Reilly
1st Edition Bambenek
https://ebookgate.com/product/grep-pocket-reference-a-quick-pocket-
reference-for-a-utility-every-unix-user-needs-pocket-reference-o-
reilly-1st-edition-bambenek/
ebookgate.com
JavaScript Pocket Reference 2nd Edition Flanagan
https://ebookgate.com/product/javascript-pocket-reference-2nd-edition-
flanagan/
ebookgate.com
Engineers Precision Data Pocket Reference Heather
https://ebookgate.com/product/engineers-precision-data-pocket-
reference-heather/
ebookgate.com
Python Essential Reference 3rd Edition Beazley
https://ebookgate.com/product/python-essential-reference-3rd-edition-
beazley/
ebookgate.com
C Pocket Reference 1st Edition Peter Prinz
https://ebookgate.com/product/c-pocket-reference-1st-edition-peter-
prinz/
ebookgate.com
Windows PowerShell pocket reference 2nd Edition Lee Holmes
https://ebookgate.com/product/windows-powershell-pocket-reference-2nd-
edition-lee-holmes/
ebookgate.com
CSS Pocket Reference 5th Edition Eric A. Meyer
https://ebookgate.com/product/css-pocket-reference-5th-edition-eric-a-
meyer/
ebookgate.com
Python pocket reference 5ed. Edition Mark Lutz
Python pocket reference 5ed. Edition Mark Lutz
Python pocket reference 5ed. Edition Mark Lutz
Mark Lutz
FIFTH EDITION
Python Pocket Reference
Python Pocket Reference, Fifth Edition
by Mark Lutz
Copyright © 2014 Mark Lutz. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebasto‐
pol, CA 95472.
O’Reillybooksmaybepurchasedforeducational,business,orsalespromotional
use. Online editions are also available for most titles (http://my.safaribookson
line.com). For more information, contact our corporate/institutional sales de‐
partment: 800-998-9938 or corporate@oreilly.com.
Editor: Rachel Roumeliotis
Production Editor: Kristen Brown
Copyeditor: Richard Carey
Proofreader: Amanda Kersey
Indexer: Lucie Haskins
Cover Designer: Randy Comer
Interior Designer: David Futato
October 1998: First Edition
January 2002: Second Edition
February 2005: Third Edition
October 2009: Fourth Edition
February 2014: Fifth Edition
Revision History for the Fifth Edition:
2014-01-17: First release
See http://oreilly.com/catalog/errata.csp?isbn=9781449357016 for release de‐
tails.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are
registered trademarks of O’Reilly Media, Inc. Python Pocket Reference, the im‐
age of a rock python, and related trade dress are trademarks of O’Reilly Media,
Inc.
Many of the designations used by manufacturers and sellers to distinguish their
products are claimed as trademarks. Where those designations appear in this
book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations
have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the
publisher and authors assume no responsibility for errors or omissions, or for
damages resulting from the use of the information contained herein.
ISBN: 978-1-449-35701-6
[M]
Table of Contents
Introduction 1
Book Conventions 2
Python Command-Line Usage 3
Python Command Options 4
Command-Line Program Specification 5
Python 2.X Command Options 7
Python Environment Variables 7
Operational Variables 8
Python Command Option Variables 9
Python Windows Launcher Usage 10
Launcher File Directives 10
Launcher Command Lines 11
Launcher Environment Variables 11
Built-in Types and Operators 12
Operators and Precedence 12
Operator Usage Notes 14
Operations by Category 16
Sequence Operation Notes 20
Specific Built-in Types 21
Numbers 22
iii
Strings 24
Unicode Strings 42
Lists 46
Dictionaries 53
Tuples 57
Files 58
Sets 63
Other Types and Conversions 65
Statements and Syntax 67
Syntax Rules 67
Name Rules 69
Specific Statements 71
The Assignment Statement 72
The Expression Statement 76
The print Statement 77
The if Statement 80
The while Statement 80
The for Statement 80
The pass Statement 81
The break Statement 81
The continue Statement 81
The del Statement 81
The def Statement 82
The return Statement 86
The yield Statement 87
The global Statement 88
The nonlocal Statement 89
The import Statement 89
The from Statement 93
The class Statement 95
The try Statement 97
The raise Statement 99
iv | Table of Contents
The assert Statement 101
The with Statement 102
Python 2.X Statements 104
Namespace and Scope Rules 105
Qualified Names: Object Namespaces 105
Unqualified Names: Lexical Scopes 105
Nested Scopes and Closures 107
Object-Oriented Programming 108
Classes and Instances 109
Pseudoprivate Attributes 110
New-Style Classes 111
Formal Inheritance Rules 112
Operator Overloading Methods 117
Methods for All Types 118
Methods for Collections (Sequences, Mappings) 123
Methods for Numbers (Binary Operators) 125
Methods for Numbers (Other Operations) 128
Methods for Descriptors 129
Methods for Context Managers 130
Python 2.X Operator Overloading Methods 131
Built-in Functions 134
Python 2.X Built-in Functions 155
Built-in Exceptions 161
Superclasses: Categories 162
Specific Exceptions 163
Specific OSError Exceptions 167
Warning Category Exceptions 169
Warnings Framework 170
Python 3.2 Built-in Exceptions 171
Python 2.X Built-in Exceptions 172
Built-in Attributes 172
Standard Library Modules 173
Table of Contents | v
The sys Module 174
The string Module 182
Functions and Classes 182
Constants 183
The os System Module 184
Administrative Tools 185
Portability Constants 186
Shell Commands 187
Environment Tools 189
File Descriptor Tools 190
File Pathname Tools 193
Process Control 197
The os.path Module 200
The re Pattern-Matching Module 202
Module Functions 202
Regular Expression Objects 205
Match Objects 205
Pattern Syntax 207
Object Persistence Modules 210
The shelve and dbm Modules 211
The pickle Module 213
The tkinter GUI Module and Tools 216
tkinter Example 216
tkinter Core Widgets 217
Common Dialog Calls 218
Additional tkinter Classes and Tools 219
Tcl/Tk-to-Python/tkinter Mappings 220
Internet Modules and Tools 221
Other Standard Library Modules 224
The math Module 224
The time Module 225
The timeit Module 226
vi | Table of Contents
The datetime Module 227
The random Module 228
The json Module 228
The subprocess Module 229
The enum Module 229
The struct Module 230
Threading Modules 231
Python SQL Database API 232
API Usage Example 233
Module Interface 234
Connection Objects 234
Cursor Objects 235
Type Objects and Constructors 236
More Hints and Idioms 236
Core Language Hints 237
Environment Hints 238
Usage Hints 240
Assorted Hints 242
Index 243
Table of Contents | vii
Python pocket reference 5ed. Edition Mark Lutz
Python Pocket Reference
Introduction
Python is a general-purpose, multiparadigm, open source com‐
puter programming language, with support for object-oriented,
functional, and procedural coding structures. It is commonly
used both for standalone programs and for scripting applications
in a wide variety of domains, and is generally considered to be
one of the most widely used programming languages in the
world.
AmongPython’sfeaturesareanemphasisoncodereadabilityand
library functionality, and a design that optimizes developer pro‐
ductivity, software quality, program portability, and component
integration.Pythonprogramsrunonmostplatformsincommon
use, including Unix and Linux, Windows and Macintosh, Java
and .NET, Android and iOS, and more.
This pocket reference summarizes Python types and statements,
special method names, built-in functions and exceptions, com‐
monly used standard library modules, and other prominent
Python tools. It is intended to serve as a concise reference tool
for developers and is designed to be a companion to other books
that provide tutorials, code examples, and other learning
materials.
This fifth edition covers both Python 3.X and 2.X. It focuses pri‐
marily on 3.X, but also documents differences in 2.X along the
1
way. Specifically, this edition has been updated to be current with
Python versions 3.3 and 2.7 as well as prominent enhancements
in the imminent 3.4 release, although most of its content also
appliesbothtoearlierandtolaterreleasesinthe3.Xand2.Xlines.
This edition also applies to all major implementations of Python
—including CPython, PyPy, Jython, IronPython, and Stackless
—and has been updated and expanded for recent changes in lan‐
guage, libraries, and practice. Its changes include new coverage
of the MRO and super(); formal algorithms of inheritance, im‐
ports, context managers, and block indentation; and commonly
used library modules and tools, including json, timeit, random,
subprocess, enum, and the new Windows launcher.
Book Conventions
The following notational conventions are used in this book:
[]
In syntax formats, items in brackets are optional; brackets
are also used literally in some parts of Python’s syntax as
noted where applicable (e.g., lists).
*
In syntax formats, items followed by an asterisk can be re‐
peated zero or more times; star is also used literally in some
parts of Python’s syntax (e.g., multiplication).
a | b
In syntax formats, items separated by a bar are alternatives;
barisalsousedliterallyinsomepartsofPython’ssyntax(e.g.,
union).
Italic
Used for filenames and URLs, and to highlight new or im‐
portant terms.
Constant width
Used for code, commands, and command-line options, and
toindicatethenamesofmodules,functions,attributes,vari‐
ables, and methods.
2 | Python Pocket Reference
Constant width italic
Used for replaceable parameter names in the syntax of com‐
mand lines, expressions, functions, and methods.
Function()
Except where noted, callable functions and methods are de‐
noted by trailing parentheses, to distinguish them from oth‐
er types of attributes.
See “Section Header Name”
Referencestoothersectionsinthisbookaregivenbysection
header text in double quotes.
NOTE
In this book, “3.X” and “2.X” mean that a topic applies to
all commonly used releases in a Python line. More specific
release numbers are used for topics of more limited scope
(e.g., “2.7” means 2.7 only). Because future Python changes
can invalidate applicability to future releases, also see
Python’s “What’s New” documents, currently maintained at
http://docs.python.org/3/whatsnew/index.html for Pythons
released after this book.
Python Command-Line Usage
Command lines used to launch Python programs from a system
shell have the following format:
python [option*]
[ scriptfile | -c command | -m module | - ] [arg*]
In this format, python denotes the Python interpreter executable
with either a full directory path, or the word python that is re‐
solved by the system shell (e.g., via PATH settings). Command-line
options intended for Python itself appear before the specification
of the program code to be run (option). Arguments intended for
the code to be run appear after the program specification (arg).
Python Command-Line Usage | 3
Python Command Options
The option items in Python command lines are used by Python
itself, and can be any of the following in Python 3.X (see “Python
2.X Command Options” ahead for 2.X differences):
-b
Issue warnings for calling str() with a bytes or bytearray
object and no encoding argument, and comparing a bytes
or bytearray with a str. Option -bb issues errors instead.
-B
Do not write .pyc or .pyo byte-code files on imports.
-d
Turn on parser debugging output (for developers of the
Python core).
-E
IgnorePythonenvironmentvariablesdescribedahead(such
as PYTHONPATH).
-h
Print help message and exit.
-i
Enter interactive mode after executing a script. Hint: useful
for postmortem debugging; see also pdb.pm(), described in
Python’s library manuals.
-O
Optimizegeneratedbytecode(createanduse.pyobyte-code
files). Currently yields a minor performance improvement.
-OO
Operates like -O, the previous option, but also removes
docstrings from byte code.
-q
Do not print version and copyright message on interactive
startup (as of Python 3.2).
4 | Python Pocket Reference
-s
Do not add the user site directory to the sys.path module
search path.
-S
Do not imply “import site” on initialization.
-u
Force stdout and stderr to be unbuffered and binary.
-v
Print a message each time a module is initialized, showing
the place from which it is loaded; repeat this flag for more
verbose output.
-V
Print Python version number and exit (also available as
--version).
-W arg
Warnings control: arg takes the form action:message:
category:module:lineno. See also “Warnings Framework”
and “Warning Category Exceptions” ahead, and the warn
ings module documentation in the Python Library Refer‐
ence manual (available at http://www.python.org/doc/).
-x
Skip first line of source, allowing use of non-Unix forms of
#!cmd.
-X option
Set implementation-specific option (as of Python 3.2); see
implementation documentation for supported option
values.
Command-Line Program Specification
Code to be run and command-line arguments to send to it are
specified in the following ways in Python command lines:
Python Command-Line Usage | 5
scriptfile
Denotes the name of a Python script file to run as the main,
topmostfileofaprogram(e.g.,python main.py runsthecode
in main.py). The script’s name may be an absolute or relative
(to “.”) filename path, and is made available in sys.argv[0].
On some platforms, command lines may also omit the
python component if they begin with a script file name and
have no options for Python itself.
-c command
Specifies Python code (as a string) to run (e.g., python -c
"print('spam' * 8)" runs a Python print operation).
sys.argv[0] is set to '-c'.
-m module
Runs a module as a script: searches for module on sys.path
and runs it as a top-level file (e.g., python -m pdb s.py runs
the Python debugger module pdb located in a standard li‐
brary directory, with argument s.py). module may also name
a package (e.g., idlelib.idle). sys.argv[0] is set to the
module’s full path name.
−
Reads Python commands from the standard input stream,
stdin (the default); enters interactive mode if stdin is a “tty”
(interactive device). sys.argv[0] is set to '−'.
arg*
Indicates that anything else on the command line is passed
to the script file or command, and appears in the built-in list
of strings sys.argv[1:].
If no scriptfile, command, or module is given, Python enters in‐
teractive mode, reading commands from stdin (and using GNU
readline for input, if installed), and setting sys.argv[0] to '' (the
empty string) unless invoked with option – in the preceding list.
Besides using traditional command lines at a system shell
prompt, you can also generally start Python programs by clicking
their filenames in a file explorer GUI; by calling functions in the
6 | Python Pocket Reference
Python standard library (e.g., os.popen()); by using program-
launch menu options in IDEs such as IDLE, Komodo, Eclipse,
and NetBeans; and so on.
Python 2.X Command Options
Python 2.X supports the same command-line format, but does
not support the -b option, which is related to Python 3.X’s string
typechanges,northerecent–qand–Xadditionsin3.X.Itsupports
additional options in 2.6 and 2.7 (some may be present earlier):
-t and -tt
Issues warnings for inconsistent mixtures of tabs and spaces
in indentation. Option -tt issues errors instead. Python 3.X
alwaystreatssuchmixturesassyntaxerrors(seealso“Syntax
Rules”).
-Q
Division-related options: -Qold (the default), -Qwarn,
-Qwarnall, and –Qnew. These are subsumed by the new true
division behavior of Python 3.X (see also “Operator Usage
Notes”).
-3
Issues warnings about any Python 3.X incompatibilities in
code that the Python standard installation’s 2to3 tool cannot
trivially fix.
-R
Enables a pseudorandom salt to make hash values of various
types be unpredictable between separate invocations of the
interpreter, as a defense against denial-of-service attacks.
New in Python 2.6.8. This switch is also present in 3.X as of
3.2.3 for compatibility, but this hash randomization is en‐
abled by default as of 3.3.
Python Environment Variables
Environment (a.k.a. shell) variables are systemwide settings that
span programs and are used for global configuration.
Python Environment Variables | 7
Operational Variables
The following are major user-configurable environment vari‐
ables related to script behavior:
PYTHONPATH
Augments the default search path for imported module files.
The format of this variable’s value is the same as the shell’s
PATH setting: directory pathnames separated by colons
(semicolons on Windows). If set, module imports search for
imported files or directories in each directory listed in
PYTHONPATH, from left to right. Merged into sys.path—the
fullmodulesearchpathforleftmostcomponentsinabsolute
imports—after the script’s directory, and before standard li‐
brary directories. See also sys.path in “The sys Module”,
and “The import Statement”.
PYTHONSTARTUP
If set to the name of a readable file, the Python commands
in that file are executed before the first prompt is displayed
in interactive mode (useful to define often-used tools).
PYTHONHOME
If set, the value is used as an alternate prefix directory for
library modules (or sys.prefix, sys.exec_prefix). The de‐
fault module search path uses sys.prefix/lib.
PYTHONCASEOK
If set, filename case is ignored in import statements (cur‐
rently only on Windows and OS X).
PYTHONIOENCODING
Assign to string encodingname[:errorhandler] to override
the default Unicode encoding (and optional error handler)
used for text transfers made to the stdin, stdout, and stderr
streams. This setting may be required for non-ASCII text in
some shells (e.g., try setting this to utf8 or other if prints
fail).
8 | Python Pocket Reference
PYTHONHASHSEED
If set to “random”, a random value is used to seed the hashes
of str, bytes, and datetime objects; may also be set to an
integerintherange0...4,294,967,295 togethashvalueswith
a predictable seed (as of Python 3.2.3 and 2.6.8).
PYTHONFAULTHANDLER
If set, Python registers handlers at startup to dump a trace‐
back on fatal signal errors (as of Python 3.3, and equivalent
to -X faulthandler).
Python Command Option Variables
The following environment variables are synonymous with some
of Python’s command-line options (see “Python Command Op‐
tions”):
PYTHONDEBUG
If nonempty, same as -d option.
PYTHONDONTWRITEBYTECODE
If nonempty, same as -B option.
PYTHONINSPECT
If nonempty, same as -i option.
PYTHONNOUSERSITE
If nonempty, same as -s option.
PYTHONOPTIMIZE
If nonempty, same as -O option.
PYTHONUNBUFFERED
If nonempty, same as -u option.
PYTHONVERBOSE
If nonempty, same as -v option.
PYTHONWARNINGS
If nonempty, same as -W option, with same value. Also ac‐
cepts a comma-separated string as equivalent to multiple -W
options. (As of Python 3.2 and 2.7.)
Python Environment Variables | 9
Python Windows Launcher Usage
OnWindows(only),Python3.3andlaterinstallascriptlauncher,
also available separately for earlier versions. This launcher con‐
sists of the executables py.exe (console) and pyw.exe (noncon‐
sole), which can be invoked without PATH settings; are registered
to run Python files via filename associations; and allow Python
versions to be selected in three ways—with “#!” Unix-like direc‐
tives at the top of scripts, with command-line arguments, and
with configurable defaults.
Launcher File Directives
The launcher recognizes “#!” lines at the top of script files that
name Python versions in one of the following forms, in which *
is either: empty to use the default version (currently 2 if installed
and similar to omitting a “#!” line); a major version number (e.g.,
3) to launch the latest version in that line installed; or a com‐
plete major.minor specification, optionally suffixed by −32 to pre‐
fer a 32-bit install (e.g., 3.1–32):
#!/usr/bin/env python*
#!/usr/bin/python*
#!/usr/local/bin/python*
#!python*
Any Python (python.exe) arguments may be given at the end of
the line, and Python 3.4 and later may consult PATH for “#!” lines
that give just python with no explicit version number.
10 | Python Pocket Reference
Launcher Command Lines
The launcher may also be invoked from a system shell with com‐
mand lines of the following form:
py [pyarg] [pythonarg*] script.py [scriptarg*]
More generally, anything that may appear in a python command
after its python component may also appear after the optional
pyarg in a py command, and is passed on to the spawned Python
verbatim. This includes the -m, -c, and - program specification
forms; see “Python Command-Line Usage”.
The launcher accepts the following argument forms for its op‐
tional pyarg, which mirror the * part at the end of a file’s “#!” line:
−2 Launch latest 2.X version installed
-3 Launch latest 3.X version installed
-X.Y Launch specified version (X is 2 or 3)
-X.Y−32 Launch the specified 32-bit version
If both are present, command-line arguments have precedence
over values given in “#!” lines. As installed, “#!” lines may be
applied in more contexts (e.g., icon clicks).
Launcher Environment Variables
The launcher also recognizes optional environment variable set‐
tings,whichmaybeusedtocustomizeversionselectionindefault
or partial cases (e.g., missing or major-only “#!” or py command
argument):
PY_PYTHON Version to use in default cases (else 2)
PY_PYTHON3 Version to use in 3 partials (e.g., 3.2)
PY_PYTHON2 Version to use in 2 partials (e.g., 2.6)
These settings are used only by launcher executables, not when
python is invoked directly.
Python Windows Launcher Usage | 11
Built-in Types and Operators
Operators and Precedence
Table1listsPython’sexpressionoperators.Operatorsinthelower
cells of this table have higher precedence (i.e., bind tighter) when
used in mixed-operator expressions without parentheses.
Atomic terms and dynamic typing
In Table 1, the replaceable expression items X, Y, Z, i, j, and k may
be:
• Variable names, replaced with their most recently assigned
value
• Literal expressions, defined in “Specific Built-in Types”
• Nested expressions, taken from any row in this table, pos‐
sibly in parentheses
Python variables follow a dynamic typing model—they are not
declared, and are created by being assigned; have object refer‐
ences as values, and may reference any type of object; and must
be assigned before appearing in expressions, as they have no de‐
fault value. Case is always significant in variable names (see
“Name Rules”). Objects referenced by variables are automatically
created, and automatically reclaimed when no longer in use by
Python’s garbage collector, which uses reference counters in
CPython.
Also in Table 1, replaceable attr must be the literal (unquoted)
name of an attribute; args1 is a formal arguments list as defined
in“ThedefStatement”;args2isaninputargumentslistasdefined
in “The Expression Statement”; and a literal ... qualifies as an
atomic expression in 3.X (only).
12 | Python Pocket Reference
The syntax of comprehensions and data structure literals (tuple,
list, dictionary, and set) given abstractly in the last three rows of
Table 1 is defined in “Specific Built-in Types”.
Table 1. Python 3.X expression operators and precedence
Operator Description
yield X Generatorfunctionresult(returnssend() value)
lambda args1: X Anonymous function maker (returns X when
called)
X if Y else Z Ternary selection (X is evaluated only if Y is true)
X or Y Logical OR: Y is evaluated only if X is false
X and Y Logical AND: Y is evaluated only if X is true
not X Logical negation
X in Y, X not in Y Membership: iterables, sets
X is Y, X is not Y Object identity tests
X < Y, X <= Y, X > Y, X >= Y Magnitude comparisons, set subset and superset
X == Y, X != Y Equality operators
X | Y Bitwise OR, set union
X ^ Y Bitwise exclusive OR, set symmetric difference
X & Y Bitwise AND, set intersection
X << Y, X >> Y Shift X left, right by Y bits
X + Y, X − Y Addition/concatenation, subtraction/set
difference
X * Y, X % Y,
X / Y, X // Y
Multiplication/repetition, remainder/format,
division, floor division
-X, +X Unary negation, identity
˜X Bitwise NOT complement (inversion)
X ** Y Power (exponentiation)
X[i] Indexing (sequence, mapping, others)
X[i:j:k] Slicing (all three bounds optional)
X(args2) Call (function, method, class, other callable)
Built-in Types and Operators | 13
Operator Description
X.attr Attribute reference
(....) Tuple, expression, generator expression
[....] List, list comprehension
{....} Dictionary, set, dictionary and set comprehension
Operator Usage Notes
• InPython2.Xonly,valueinequalitycanbewrittenaseither
X != Y or X <> Y. In Python 3.X, the latter of these options is
removed because it is redundant.
• In Python 2.X only, a backquotes expression `X` works the
same as repr(X), and converts objects to display strings. In
Python 3.X, use the more readable str() and repr() built-
in functions instead.
• In both Python 3.X and 2.X, the X // Y floor division ex‐
pression always truncates fractional remainders, and re‐
turns an integer result for integers.
• The X / Y expression performs true division in 3.X (always
retaining remainders in a floating-point result), and classic
division in 2.X (truncating remainders for integers) unless
3.X’s true division is enabled in 2.X with from __future__
import division or Python option -Qnew.
• The syntax [....] is used for both list literals and list com‐
prehension expressions. The latter of these performs an
implied loop and collects expression results in a new list.
• The syntax (....) is used for tuples and expressions, as
well as generator expressions—a form of list comprehen‐
sion that produces results on demand, instead of building
a result list. Parentheses may sometimes be omitted in all
three constructs.
14 | Python Pocket Reference
• The syntax {....} is used for dictionary literals. In Python
3.X and 2.7, it is also used for set literals, and both dictio‐
nary and set comprehensions; use set() and looping state‐
ments in 2.6 and earlier.
• The yield and ternary if/else selection expressions are
availableinPython2.5andlater.Theformerreturnssend()
arguments in generators; the latter is a shorthand for a
multiline if statement. yield requires parentheses if not
alone on the right side of an assignment statement.
• Comparison operators may be chained: X < Y < Z produces
the same result as X < Y and Y < Z, but Y is evaluated only
once in the chained form.
• The slice expression X[i:j:k] is equivalent to indexing
with a slice object: X[slice(i, j, k)].
• In Python 2.X, magnitude comparisons of mixed types are
allowed—converting numbers to a common type, and or‐
dering other mixed types according to the type name. In
Python 3.X, nonnumeric mixed-type magnitude compar‐
isons are not allowed and raise exceptions; this includes
sorts by proxy.
• Magnitude comparisons for dictionaries are also no longer
supported in Python 3.X (although equality tests are);
comparingsorted(adict.items()) isonepossiblereplace‐
ment in 3.X.
• Call expressions allow for positional and keyword argu‐
ments, and arbitrarily large numbers of both; see “The Ex‐
pression Statement” and “The def Statement” for call
syntax.
• Python 3.X allows ellipsis (literally, ..., and known by
built-in name Ellipsis) to be used as an atomic expression
anywhereinsourcecode.Thismaybeusedasanalternative
topass orNone insomecontexts(e.g.,stubbed-outfunction
bodies, type-independent variable initialization).
Built-in Types and Operators | 15
• Although uncertain at this writing, Python 3.5 or later may
generalize the *X and **X star syntax to appear in data
structureliteralsandcomprehensions,whereitwillunpack
collections into individual items, much as it currently does
infunctioncalls.See“TheAssignmentStatement”formore
details.
Operations by Category
In this section, trailing parentheses are omitted from __X__
method names for brevity. In general, all built-in types support
the comparisons and Boolean operations listed in Table 2 (al‐
though Python 3.X does not support magnitude comparisons for
dictionaries or mixed nonnumeric types).
Boolean true means any nonzero number or any nonempty col‐
lectionobject(list,dictionary,etc.),andallobjectshaveaBoolean
value. The built-in names True and False are preassigned to true
and false values and behave like integers 1 and 0 with custom
display formats. The special object None is false and appears in
various Python contexts.
Comparisons return True or False and are automatically applied
recursively in compound objects as needed to determine a result.
Boolean and and or operators stop (short-circuit) as soon as a
result is known and return one of the two operand objects—the
value on the left or the right of the operator—whose Boolean
value gives the result.
Table 2. Comparisons and Boolean operations
Operator Description
X < Y Strictly less thana
X <= Y Less than or equal to
X > Y Strictly greater than
X >= Y Greater than or equal to
X == Y Equal to (same value)
16 | Python Pocket Reference
Operator Description
X != Y Not equal to (same as X<>Y in Python 2.X
only)b
X is Y Same object
X is not Y Negated object identity
X < Y < Z Chained comparisons
not X If X is false then True; else, False
X or Y If X is false then Y; else, X
X and Y If X is false then X; else, Y
aToimplementcomparisonexpressions,seeboththerichcomparison(e.g.,__lt__
for<)classmethodsin3.Xand2.X,andgeneral__cmp__methodin2.X,described
in “Operator Overloading Methods”.
b != and <> both mean not equal by value in 2.X, but != is the preferred syntax
in 2.X and the only supported option in 3.X. is performs an identity test; ==
performs value comparison, and so is much more generally useful.
Tables 3 through 6 define operations common to types in the
three major type categories—sequence (positionally ordered),
mapping (access-by-key), and number (all numeric types)—as
well as operations available for mutable (changeable) types in
Python. Most types also export additional type-specific opera‐
tions (e.g., methods), as described in “Specific Built-in Types”.
Table 3. Sequence operations (strings, lists, tuples, bytes, bytearray)
Operation Description Class method
X in S
X not in S
Membership tests __contains__,
__iter__,
__getitem__a
S1 + S2 Concatenation __add__
S * N, N * S Repetition __mul__
S[i] Index by offset __getitem__
Built-in Types and Operators | 17
Operation Description Class method
S[i:j], S[i:j:k] Slicing: items in S from
offset i through j−1 by
optional stride k
__getitem__b
len(S) Length __len__
min(S), max(S) Minimum, maximum item __iter__,
__getitem__
iter(S) Iteration protocol __iter__
for X in S:,
[expr for X in S],
map(func, S), etc.
Iteration (all contexts) __iter__,
__getitem__
a See also “The iteration protocol” for more on these methods and their interplay.
If defined, __contains__ is preferred over __iter__, and __iter__ is
preferred over __getitem__.
b In Python 2.X, you may also define __getslice__, __setslice__, and
__delslice__ to handle slicing operations. In 3.X, these are removed in favor
ofpassingsliceobjectstotheiritem-basedindexingcounterparts.Sliceobjectsmay
be used explicitly in indexing expressions in place of i:j:k bounds.
Table 4. Mutable sequence operations (lists, bytearray)
Operation Description Class method
S[i] = X Index assignment: change item at existing
offset i to reference X
__setitem__
S[i:j] = I,
S[i:j:k] = I
Slice assignment: S from i through j−1
with optional stride k (possibly empty) is
replaced by all items in iterable I
__setitem__
del S[i] Index deletion __delitem__
del S[i:j],
del S[i:j:k]
Slice deletion __delitem__
18 | Python Pocket Reference
Table 5. Mapping operations (dictionaries)
Operation Description Class method
D[k] Index by key __getitem__
D[k] = X Key assignment: change or
create entry for key k to
reference X
__setitem__
del D[k] Delete item by key __delitem__
len(D) Length (number of keys) __len__
k in D Key membership testa Same as in Table 3
k not in D Converse of k in D Same as in Table 3
iter(D) Iterator object for D’s keys Same as in Table 3
for k in D:, etc. Iterate through keys in D (all
iteration contexts)
Same as in Table 3
a In Python 2.X, key membership may also be coded as D.has_key(k). This
method is removed in Python 3.X in favor of the in expression, which is also
generally preferred in 2.X. See “Dictionaries”.
Table 6. Numeric operations (all number types)
Operation Description Class method
X + Y, X − Y Add, subtract __add__, __sub__
X * Y, X / Y,
X // Y, X % Y
Multiply, divide, floor
divide, remainder
__mul__, __truediv__a,
__floordiv__, __mod__
−X, +X Negative, identity __neg__, __pos__
X | Y, X & Y,
X ^ Y
Bitwise OR, AND,
exclusive OR (integers)
__or__, __and__, __xor__
X << N, X >> N Bitwiseleft-shift,right-
shift (integers)
__lshift__, __rshift__
˜X Bitwise invert
(integers)
__invert__
X ** Y X to the power Y __pow__
abs(X) Absolute value __abs__
Built-in Types and Operators | 19
Operation Description Class method
int(X) Convert to integerb __int__
float(X) Convert to float __float__
complex(X),
complex(re,im)
Make a complex value __complex__
divmod(X, Y) Tuple: (X / Y, X % Y) __divmod__
pow(X, Y [,Z]) Raise to a power __pow__
a The / operator invokes __truediv__ in Python 3.X, but __div__ in Python 2.X
unless true division is enabled. See “Operator Usage Notes” for division semantics.
b In Python 2.X, the long() built-in function invokes the __long__ class method.
In Python 3.X, the int type subsumes long, which is removed.
Sequence Operation Notes
Examples and notes on selected sequence operations in Table 3
and Table 4:
Indexing: S[i]
• Fetches components at offsets (first item is at offset 0).
• Negative indexes count backward from the end (last item
is at offset −1).
• S[0] fetches the first item; S[1] fetches the second item.
• S[−2] fetches the second-to-last item (same as S[len(S)
− 2]).
Slicing: S[i:j]
• Extracts contiguous sections of a sequence, from i through
j−1.
• Slice boundaries i and j default to 0 and sequence length
len(S).
• S[1:3] fetches from offsets 1 up to, but not including, 3.
• S[1:] fetches from offsets 1 through the end (len(S)-1).
20 | Python Pocket Reference
• S[:−1] fetches from offsets 0 up to, but not including, the
last item.
• S[:] makes a top-level (shallow) copy of sequence object S.
Extended slicing: S[i:j:k]
• The third item k is a stride (default 1), added to the offset
of each item extracted.
• S[::2] is every other item in entire sequence S.
• S[::−1] is sequence S reversed.
• S[4:1:−1] fetches from offsets 4 up to, but not including,
1, reversed.
Slice assignment: S[i:j:k] = I
• Slice assignment is similar to deleting and then inserting
where deleted.
• Iterables assigned to basic slices S[i:j] need not match in
size.
• Iterables assigned to extended slices S[i:j:k] must match
in size.
Other
• Concatenation, repetition, and slicing return new objects
(though not always for tuples).
Specific Built-in Types
This section covers numbers, strings, lists, dictionaries, tuples,
files,sets,andothercorebuilt-intypes.Itssubsectionsgivedetails
common to both Python 3.X and 2.X. In general, all the
compound datatypes covered here (e.g., lists, dictionaries, and
tuples) can nest inside each other arbitrarily and as deeply as
Specific Built-in Types | 21
1. InPython2.X,thereisadistincttypenamedlongforunlimited-precision
integers; int is for normal integers with precision that is usually limited
to 32 bits. Long objects may be coded with a trailing “L” (e.g., 99999L),
although integers are automatically promoted to longs if they require the
extra precision. In 3.X, the int type provides unlimited precision and so
subsumes both the 2.X int and long types; the “L” literal syntax is re‐
moved in 3.X.
2. In Python 2.X, octal literals may also be written with just a leading zero
—0777and0o777areequivalent.In3.X,onlythelatterformissupported
for octal.
required. Sets may participate in nesting as well, but may contain
only immutable objects.
Numbers
Numbers are immutable (unchangeable) values, supporting nu‐
meric operations. This section covers basic number types (inte‐
gers, floating-point), as well as more advanced types (complex,
decimals, and fractions).
Literals and creation
Numbers are written in a variety of numeric literal forms, and
created by some built-in operations:
1234, −24, +42, 0
Integers (unlimited precision).1
1.23, 3.14e-10, 4E210, 4.0e+210, 1., .1
Floating-point (normally implemented as C doubles in
CPython).
0o177, 0x9ff, 0b1111
Octal, hex, and binary literals for integers.2
3+4j, 3.0+4.0j, 3J
Complex numbers.
22 | Python Pocket Reference
decimal.Decimal('1.33'), fractions.Fraction(4, 3)
Module-based types: decimal, fraction.
int(9.1), int('-9'), int('1111', 2), int('0b1111', 0),
float(9), float('1e2'), float('-.1'), complex(3, 4.0)
Create numbers from other objects, or from strings with
possible base conversion. Conversely, hex(N), oct(N), and
bin(N) createdigitstringsforintegers,andstringformatting
makes general strings for numbers. See also “String format‐
ting”, “Type Conversions”, and “Built-in Functions”.
Operations
Number types support all number operations (see Table 6 on page
19). In mixed-type expressions, Python converts operands up to
thetypeofthe“highest”type,whereintegerislowerthanfloating-
point, which is lower than complex. As of Python 3.0 and 2.6,
integer and floating-point objects also have a handful of type-
specific methods and other attributes; see Python’s Library Ref‐
erence manual for details:
>>> (2.5).as_integer_ratio() # float attrs
(5, 2)
>>> (2.5).is_integer()
False
>>> (2).numerator, (2).denominator # int attrs
(2, 1)
>>> (255).bit_length(), bin(255) # 3.1+ method
(8, '0b11111111')
Decimal and fraction
Python provides two additional numeric types in standard li‐
brary modules—decimal is a fixed-precision, floating-point
number, and fraction is a rational type that keeps numerator and
denominatorexplicitly.Bothmaybeusedtoaddressinaccuracies
of floating-point arithmetic:
>>> 0.1 - 0.3
-0.19999999999999998
Specific Built-in Types | 23
>>> from decimal import Decimal
>>> Decimal('0.1') - Decimal('0.3')
Decimal('-0.2')
>>> from fractions import Fraction
>>> Fraction(1, 10) - Fraction(3, 10)
Fraction(-1, 5)
>>> Fraction(1, 3) + Fraction(7, 6)
Fraction(3, 2)
Fractions automatically simplify results. By fixing precision and
supporting various truncation and rounding protocols, decimals
are useful for monetary applications. See the Python Library Ref‐
erence for details.
Other numeric types
Python also includes a set type (described in “Sets”). Additional
numeric types such as optimized vectors and matrixes are avail‐
able as third-party open source extensions (e.g., see the NumPy
package at http://www.numpy.org). The third-party domain also
includes support for visualization, statistical tools, extended pre‐
cision floating-point math, and more (see the Web).
Strings
The normal str string object is an immutable (unchangeable)
sequence of characters accessed by offset (position). Its charac‐
ters are code point ordinals in the underlying character set, and
individual characters are string objects of length 1.
The full string object model varies across lines.
Python 3.X has three string types with similar interfaces:
str
An immutable sequence of characters, used for all text—
both ASCII and richer Unicode.
24 | Python Pocket Reference
bytes
An immutable sequence of short integers, used for the byte
values of binary data.
bytearray
A mutable variant of bytes.
Python 2.X instead has two string types with similar interfaces:
str
An immutable sequence of characters, used for both byte
oriented (8-bit) text and binary data.
unicode
An immutable sequence of characters, used for possibly-
richer Unicode text.
Python 2.X (as of 2.6) also has the Python 3.X bytearray type as
aback-portfrom3.X,butitdoesnotimposeassharpadistinction
between text and binary data. (It may be mixed with text strings
freely in 2.X.)
For Unicode support in both 3.X and 2.X, see “Unicode
Strings”. Most of the remainder of this section pertains to all
string types, but see “String methods”, “Unicode Strings”, and
“Built-in Functions” for more on bytes and bytearray.
Literals and creation
String literals are written as a series of characters in quotes, op‐
tionally preceded with a designator character, and in all string
literal forms an empty string is coded as adjacent quotes. Various
built-in operations also return new strings:
'Python"s', "Python's"
Single and double quotes work the same, and each can em‐
bed unescaped quotes of the other kind.
"""This is a multiline block"""
Triple-quoted blocks collect multiple lines of text into a sin‐
gle string, with end-of-line markers (n) inserted between
the original quoted lines.
Specific Built-in Types | 25
'Python'sn'
Backslash escape code sequences (see Table 7) are replaced
with the special-character code point values they represent
(e.g., 'n' is an ASCII character with decimal code-point
value 10).
"This" "is" "concatenated"
Adjacent string constants are concatenated. Hint: this form
may span lines if parenthesized.
r'a rawstring', R'anotherone'
Raw strings: backslashes are retained literally (except at the
endofastring).UsefulforregularexpressionsandWindows
(DOS) directory paths: e.g., r'c:dir1file'.
hex(), oct(), bin()
Create hex/octal/binary digit strings from integer numbers.
See “Numbers” and “Built-in Functions”.
The following literal forms and calls make specialized strings de‐
scribed in “Unicode Strings”:
b'...'
bytes string literal in Python 3.X: sequence of 8-bit byte
values representing raw binary data. For 3.X compatibility,
this form is also available in Python 2.6 and 2.7, where it
simply creates a normal str string. See “String methods”,
“Unicode Strings”, and “Built-in Functions”.
bytearray(...)
bytearray string construction: a mutable variant of bytes.
Available in Python 3.X, and in Python 2.X as of 2.6. See
“String methods”, “Unicode Strings”, and “Built-in Func‐
tions”.
u'...'
Unicode string literal in Python 2.X: a sequence of Unicode
code points. For 2.X compatibility, this form is also available
in Python 3.X as of 3.3, where it simply creates a normal str
string (but normal string literals and str strings support
Unicode text in Python 3.X). See “Unicode Strings”.
26 | Python Pocket Reference
str(), bytes(), bytearray() (and unicode() in 2.X only)
Create strings from objects, with possible Unicode encod‐
ing/decoding in Python 3.X. See “Built-in Functions”.
String literals may contain escape sequences taken from Table 7
to represent special characters.
Table 7. String constant escape codes
Escape Meaning Escape Meaning
newline Ignored
continuation
t Horizontal tab
 Backslash () v Vertical tab
' Single quote (‘) N{id} Unicode dbase id
" Double quote (“) uhhhh Unicode 16-bit hex
a Bell Uhhhhhhhh Unicode 32-bit hexa
b Backspace xhh Hex (at most 2 digits)
f Formfeed ooo Octal (up to 3 digits)
n Line feed 0 Null (not end of string)
r Carriage return other Not an escape
a Uhhhhhhhh takes exactly eight hexadecimal digits (h); both u and U can
be used only in Unicode string literals.
Operations
All string types support all sequence operations (see Table 3), plus
string-specific methods (described in “String methods”). In ad‐
dition, the str type supports string formatting % expressions and
template substitution (discussed next), and the bytearray type
supportsmutable sequence operations(Table4,plusextralist-like
methods). Also see the re string pattern-matching module in
“The re Pattern-Matching Module”, and string-related, built-in
functions in “Built-in Functions”.
Specific Built-in Types | 27
String formatting
In both Python 3.X and 2.X (as of 3.0 and 2.6), normal str strings
support two different flavors of string formatting—operations
that format objects according to format description strings:
• The original expression (all Python versions), coded with
the % operator: fmt % (values)
• The newer method (3.0, 2.6, and later), coded with call
syntax: fmt.format(values)
Both produce new strings based on possibly type-specific sub‐
stitution codes. Their results may be displayed, or assigned to
variables for later use:
>>> '%s, %s, %.2f' % (42, 'spam', 1 / 3.0)
'42, spam, 0.33'
>>> '{0}, {1}, {2:.2f}'.format(42, 'spam', 1 / 3.0)
'42, spam, 0.33'
Although the method call seems to have evolved more rapidly in
recent years, the expression is used extensively in existing code,
and both forms are still fully supported. Moreover, although
some view the method form as marginally more mnemonic and
consistent, the expression is often simpler and more concise. As
these two forms are largely just minor variations on a theme of
equivalent functionality and complexity, there is today no com‐
pelling reason to recommend one over the other.
String formatting expression
String formatting expressions replace % targets in the string on the
left of the % operator, with values on the right (similar to C’s
sprintf). If more than one value is to be replaced, they must be
coded as a tuple to the right of the % operator. If just one item is
to be replaced, it can be coded as a single value or one-item tuple
on the right (nest tuples to format a tuple itself). If key names are
used on the left, a dictionary must be supplied on the right, and
* allows width and precision to be passed in dynamically:
28 | Python Pocket Reference
>>> 'The knights who say %s!' % 'Ni'
'The knights who say Ni!'
>>> '%d %s, %d you' % (1, 'spam', 4.0)
'1 spam, 4 you'
>>> '%(n)d named %(x)s' % {'n': 1, 'x': "spam"}
'1 named spam'
>>> '%(n).0E => [%(x)-6s]' % dict(n=100, x='spam')
'1E+02 => [spam ]'
>>> '%f, %.2f, %+.*f' % (1/3.0, 1/3.0, 4, 1/3.0)
'0.333333, 0.33, +0.3333'
Formatting expression syntax
In the format string on the left of the % operator, substitution
targets have the following general format, all but the last com‐
ponentofwhichisoptional(textoutsidesuchsubstitutiontargets
is retained verbatim):
%[(keyname)][flags][width][.prec]typecode
In this substitution target syntax:
keyname
References an item in the expected dictionary, in
parentheses.
flags
Can be − (left-justify), + (numeric sign), a space (use a blank
before positive numbers and a − for negatives ), and 0 (zero
fill).
width
The total minimum field width (use * to fetch from values).
prec
Gives the number of digits (i.e., precision) to include af‐
ter . (use * to fetch from values).
typecode
A character from Table 8.
Specific Built-in Types | 29
Both width and prec can be coded as a * to force their values to
be taken from the next item in the values to the right of the %
operator when sizes are not known until runtime. Hint: %s ge‐
nerically converts any object type to its print representation
string.
Table 8. % string formatting type codes
Code Meaning Code Meaning
s String (or any object, uses str()) X x with uppercase
r s, but uses repr(), not str() e Floating-point exponent
c Character (int or str) E e with uppercase
d Decimal (base 10 integer) f Floating-point decimal
i Integer F f with uppercase
u Same as d (obsolete) g Floating-point e or f
o Octal (base 8 integer) G Floating-point E or F
x Hex (base 16 integer) % Literal ‘%’ (coded as %%)
String formatting method
The formatting method call works similar to the prior section’s
expression, but is invoked with normal method-call syntax on
theformatstringobject,whichidentifiessubstitutiontargetswith
{} syntax instead of %.
Substitution targets in the format string may name method-call
arguments by position or keyword name; may further reference
argument attributes, keys, and offsets; may accept default for‐
mattingorprovideexplicittypecodes;andmaynesttargetsyntax
to pull values from the arguments list:
>>> 'The knights who say {0}!'.format('Ni')
'The knights who say Ni!'
>>> '{0} {1}, {2:.0f} you'.format(1, 'spam', 4.0)
'1 spam, 4 you'
>>> '{n} named {x:s}'.format(n=1, x="spam")
'1 named spam'
>>> '{n:.0E} => [{x:<6s}]'.format(
**dict(n=100, x='spam'))
30 | Python Pocket Reference
'1E+02 => [spam ]'
>>> '{:f}, {:.2f}, {:+.{}f}'.format(
1/3.0, 1/3.0, 1/3.0, 4)
'0.333333, 0.33, +0.3333'
Most format method applications have equivalents in % expres‐
sion usage patterns as shown in the preceding section (e.g., dic‐
tionary key and * value references), although the method allows
some operations to be coded inside the format string itself:
>>> import sys # Method vs expr: attr, key, index
>>> fmt = '{0.platform} {1[x]} {2[0]}'
>>> fmt.format(sys, dict(x='ham'), 'AB')
'win32 ham A'
>>> fmt = '%s %s %s'
>>> fmt % (sys.platform, dict(x='ham')['x'], 'AB'[0])
'win32 ham A'
As of Python 3.1 and 2.7, a , (comma) preceding an integer or
floating-point designation in typecode, formally described in
“Formatting method syntax”, inserts thousands-separator com‐
mas, and a typecode of % formats a percentage (tools not present
in the formatting expression itself, but straightforward to code
as reusable functions):
>>> '{0:,d}'.format(1000000)
'1,000,000'
>>> '{0:13,.2f}'.format(1000000)
' 1,000,000.00'
>>> '{0:%} {1:,.2%}'.format(1.23, 1234)
'123.000000% 123,400.00%'
Also as of Python 3.1 and 2.7, field numbers are automatically
numbered sequentially if omitted from the fieldname also de‐
scribed in “Formatting method syntax”—the following three
have the same effect, although auto-numbered fields may be less
readable if many fields are present:
>>> '{0}/{1}/{2}'.format('usr', 'home', 'bob')
'usr/home/bob'
>>> '{}/{}/{}'.format('usr', 'home', 'bob') # Auto
Specific Built-in Types | 31
'usr/home/bob'
>>> '%s/%s/%s' % ('usr', 'home', 'bob') # Expr
'usr/home/bob'
A single object may also be formatted with the format(object,
formatspec) built-in function (see “Built-in Functions”), which
is employed by the string format method, and whose behavior
may be implemented with the __format__ operator-overloading
method in classes (see “Operator Overloading Methods”).
Formatting method syntax
Substitution targets in strings used for format method calls take
the following general form, all four parts of which are optional,
and must appear without intervening spaces (used here for clari‐
ty):
{fieldname component !conversionflag :formatspec}
In this substitution target syntax:
fieldname
An optional number or keyword identifying an argument,
which may be omitted to use relative argument numbering
in 2.7, 3.1, and later.
component
A string of zero or more .name or [index] references used
to fetch attributes and indexed values of the argument,
which may be omitted to use the whole argument value.
conversionflag
Introduced by a ! if present, which is followed by r, s, or a
to call repr(), str(), or ascii() built-in functions on the
value, respectively.
formatspec
Introducedbya: ifpresent,andconsistsoftextthatspecifies
how the value should be presented, including details such
as field width, alignment, padding, decimal precision, and
so on, and ending with an optional datatype code.
32 | Python Pocket Reference
The nested formatspec component after the colon character has
a syntax of its own, formally described as follows (brackets in this
denote optional components and are not coded literally):
[[fill]align][sign][#][0][width][,][.prec][typecode]
In this formatspec nested syntax:
fill
Can be any fill character other than { or }.
align
May be <, >, =, or ^, for left alignment, right alignment,
padding after a sign character, or centered alignment,
respectively.
sign
May be +, −, or space.
, (comma)
Requests a comma for a thousands separator as of Python
3.1 and 2.7.
width and prec
Much as in the % expression, and the formatspec may also
contain nested {} format strings having a fieldname only, to
take values from the arguments list dynamically (much like
the * in formatting expressions). A 0 preceding width ena‐
bles sign-aware zero padding (similar to fill), and a # en‐
ables an alternative conversion (if available).
typecode
Largely the same as in % expressions and listed in Table 8,
but the format method has an extra b type code used to give
integers in binary format (much like using the bin built-in);
has an extra % type code to format percentages as of Python
3.1 and 2.7; and uses only d for base-10 integers (i or u are
not used).
Note that unlike the expression’s generic %s, the method’s s type
code requires a string object argument; omit the type code to
accept any type generically in the method.
Specific Built-in Types | 33
Template string substitution
As of Python 2.4, another form of string substitution is provided
as an alternative to the string formatting expression and method
described in the prior sections. In full formatting, substitution is
achieved with the % operator or str.format() method (all four of
the following return '2: PR5E'):
'%(page)i: %(book)s' % {'page': 2, 'book': 'PR5E'}
'%(page)i: %(book)s' % dict(page=2, book='PR5E')
'{page}: {book}'.format(**dict(page=2, book='PR5E'))
'{page}: {book}'.format(page=2, book='PR5E')
For simpler substitution tasks, a Template class in string uses $
to indicate a substitution:
>>> import string
>>> t = string.Template('$page: $book')
>>> t.substitute({'page': 2, 'book': 'PR5E'})
'2: PR5E'
Substitution values can be provided as keyword arguments or
dictionary keys:
>>> s = string.Template('$who likes $what')
>>> s.substitute(who='bob', what=3.14)
'bob likes 3.14'
>>> s.substitute(dict(who='bob', what='pie'))
'bob likes pie'
A safe_substitute method ignores missing keys rather than
raising an exception:
>>> t = string.Template('$page: $book')
>>> t.safe_substitute({'page': 3})
'3: $book'
String methods
In addition to the format() method described earlier, string
method calls provide higher-level text processing tools beyond
string expressions. Table 9 lists available string method calls; in
this table, S is any string object (technically, a 3.X str). String
34 | Python Pocket Reference
methods that modify text always return a new string and never
modify the object in-place (strings are immutable).
For more details on methods in the table, see the functional area
description sections ahead, or run a help(str.method) interac‐
tively. Hint: this list can vary across Python releases; to see yours,
try:
sorted(x for x in dir(str) if not x.startswith('__'))
See also the re module in “The re Pattern-Matching Module” for
pattern-based equivalents to some string type methods.
Table 9. Python 3.X string method calls
S.capitalize()
S.casefold() (as of Python 3.3)
S.center(width, [, fill])
S.count(sub [, start [, end]])
S.encode([encoding [, errors]])
S.endswith(suffix [, start [, end]])
S.expandtabs([tabsize])
S.find(sub [, start [, end]])
S.format(*args, **kwargs)
S.format_map(mapping) (as of Python 3.2)
S.index(sub [, start [, end]])
S.isalnum()
S.isalpha()
S.isdecimal()
S.isdigit()
S.isidentifier()
S.islower()
S.isnumeric()
S.isprintable()
Specific Built-in Types | 35
Another Random Document on
Scribd Without Any Related Topics
Python pocket reference 5ed. Edition Mark Lutz
Python pocket reference 5ed. Edition Mark Lutz
Python pocket reference 5ed. Edition Mark Lutz
The Project Gutenberg eBook of Virginia's
Adventure Club
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.
Title: Virginia's Adventure Club
Author: Grace May North
Illustrator: Elizabeth Colborne
Thelma Gooch
Release date: May 1, 2020 [eBook #61987]
Most recently updated: October 17, 2024
Language: English
Credits: Produced by Roger Frank and the Online Distributed
Proofreading Team at https://www.pgdp.net (This file
was
produced from images generously made available by
The
Internet Archive)
*** START OF THE PROJECT GUTENBERG EBOOK VIRGINIA'S
ADVENTURE CLUB ***
Python pocket reference 5ed. Edition Mark Lutz
VIRGINIA’S ADVENTURE CLUB
“I’m not scared of you,” she said.
VIRGINIA’S ADVENTURE CLUB
By
GRACE MAY NORTH
Author of
“Virginia of V. M. Ranch,” “Virginia at Vine Haven,”
“Virginia’s Ranch Neighbors,” “Virginia’s Romance.”
A. L. BURT COMPANY
Publishers New York
Printed in U. S. A.
THE
VIRGINIA DAVIS SERIES
A SERIES OF STORIES FOR GIRLS OF
TWELVE TO SIXTEEN YEARS OF AGE
By GRACE MAY NORTH
VIRGINIA OF V. M. RANCH
VIRGINIA AT VINE HAVEN
VIRGINIA’S ADVENTURE CLUB
VIRGINIA’S RANCH NEIGHBORS
VIRGINIA’S ROMANCE
Copyright, 1924
By A. L. BURT COMPANY
VIRGINIA’S ADVENTURE CLUB
Made in “U. S. A.”
VIRGINIA’S ADVENTURE CLUB
CHAPTER I
THE ADVENTURE CLUB
“Now that the Christmas holidays are over,” Babs remarked on the
first Monday evening after the close of the short vacation, “I mean
to redeem myself.”
Margaret Selover looked down at the Dresden China girl who, her
fluffy golden curls loosened from their fastenings, was wearing a
blue corduroy kimona which matched her eyes. Babs sat tailorwise
upon the furry white rug close to their grate fire.
Megsy laughed. “Which means?” she inquired as she sat in front
of her birds-eye maple dressing table, brushing her pretty brown
hair.
“Which means that I have determined to startle the natives by
getting my name on the honor roll. Watchez-vous me! See if I don’t.”
“I certainly admire your French.” Margaret was donning her
golden brown robe that was woolly and warm. Then, when she, too,
was seated opposite her roommate, she inquired: “But why this
sudden ambition? I thought your motto has always been ‘Learn as
little as you can, for wisdom makes a stupid man.’”
“Well, doesn’t it?” Babs flashed. “Take Professor Crowell fer
instance. He probably knows as much as the encyclopædia, and yet,
who can deny but that he is stupid. He goes around ruminating on
things that nobody else could understand, and he can’t even tell his
own daughters apart.”
Margaret laughed. “Well, belovedest, I don’t think you and I are
either of us in danger of becoming as wise as Professor Crowell, and
as for telling Dora and Cora apart—who can? Certainly not Mrs.
Martin, and they’ve been in this school since they were small.” Then
more seriously, she clasped her hands over her drawn-up knees,
Margaret continued: “But I would like to be as wise as Miss
Torrence. When she is reading to us and there is a reference to
someone or something that happened in the long ago, you know
how her eyes brighten. She is seeing a picture that represents it. I
know, because yesterday when I came across a reference to the
Peripatetic school, I was as pleased as Punch. I knew at once that
the Greek word meant ‘to walk,’ and that it had been used because
Aristotle, the greatest of ancient philosophers, walked up and down
in his garden while teaching. And so I have decided that, if learning
does nothing else, it adds a lot to one’s own pleasure.”
Babs glanced at the clock over the mantle. “I don’t see why the
girls don’t come,” she said, trying to suppress a little yawn. Margaret
laughed and leaned over to poke up the fire. “My professorial
discourse has evidently made you sleepy. Hark! I believe I hear
approaching giggles.”
A merry tattoo on the closed door announced the arrival of the
expected guests, and in they trooped, each wearing a bath robe or
warm kimona of the color which the owner believed to be most
becoming to her particular type of beauty.
Betsy Clossen, in a brilliant cherry-red robe, was the first to burst
in. Then, observing the solemn faces of the two before the fire, she
remarked inelegantly: “For Pete’s sake, who died? I thought we were
going to have a giggle-fest to celebrate our reunion, after the long
separation, and here are our hostesses looking as though they had
just heard that they’d both failed in the final tests.”
The newcomers dropped down on chairs or floor, as they
preferred. Barbara continued to look unusually solemn. “That’s just
it,” she announced. Then to Margaret: “That’s why I told you awhile
ago that I mean to redeem myself. I flunked on the holiday tests,
and I was the only one in our crowd who did. Even Betsy—” She
paused and there was a mischievous twinkle in the blue eyes that
had been serious longer than was their wont.
“Believe me, I just got through by the skin of my teeth!” that
maiden announced in her characteristic manner. “Spent too much
time playing detective, and failed at that, too.”
“I’ll tell you what!” Virginia Davis, who had been a sympathetic
listener, spoke for the first time. “Let’s have a study club and meet in
one of our rooms every Saturday evening and have an oral review of
the week’s work.”
“Ooh!” moaned Betsy; “that doesn’t sound very interesting.”
“I’m for it,” Babs announced; “and when the grind part is over,
couldn’t we have refreshments?” This, hopefully.
“Why, of course. We are always allowed to make fudge on
Saturday evening—” Virginia had begun, when Betsy put in: “Oh, I
say; please change the name of it; then I’ll enjoy it heaps more, if
one can enjoy anything related to learning.”
“Can’t we think up some name that won’t sound the least bit
studious? Then we can have the real object a secret.”
“We might call it The Adventure Club if you would enjoy the
meetings more than you would if we called it The Weekly Review.”
Margaret smilingly suggested.
“I’m for it,” Betsy declared, then added doubtfully. “I suppose my
new roommate will think she ought to be let in on it. Would any of
you mind? She’s not such a bad sort.”
“Who did you draw, Bets? I thought you hoped you were to have
your room alone this term.”’
“So did I, but Fate was agin’ me. Just as I was spreading my duds
all over the room, thinking I was to be sole possessor, along came
Mrs. Martin with a roommate for me. Since Sally MacLean didn’t
come the first term, I didn’t ever expect her back again.”
“Sentimental Sally!” Babs and Megsy exclaimed in one breath.
“Has she returned to Vine Haven?”
A doleful nod was Betsy’s only reply. Then she laughed gaily as
though at some merry memory. “I suppose you girls who don’t know
her are wondering why we call her ‘Sentimental Sally,’ and so I’ll tell
you.”
“Well, proceed. We’re all ears, as the elephant’s child was once
heard to remark,” Barbara said as she leaned back against Virginia,
who sat in the easy willow chair.
“Is this Sentimental Sally, silly?” Virg inquired.
Betsy laughed. “Silly?” she repeated with rising inflection, “She’s
worse than that. She’s bugs! Or rather, she was. I sort of think she’s
cured. Time alone will tell.”
“Sally is always in love or thinks she is, which is perfectly
ridiculous,” Margaret explained, “since she is only fifteen.”
“I’ve sometimes thought that if Sally had had brothers, as we
have, she wouldn’t have had such foolish notions,” Barbara
remarked. “You have the floor now, Betsy, tell the girls the woeful
tale of Sally’s downfall.”
“Well, to begin at the beginning, Miss Snoopins, otherwise known
as the Belligerent Buell, is death on members of the sex not fair.”
“Meaning boys,” Barbara put in.
“One of the rules that she made for the corridors was that no
photographs of the objectionable creatures should be displayed in
our rooms. Well, as usual, Sally was being sentimental about
somebody, and the somebody was certainly a most good-looking
boy. She called him ‘Donald Dear’ and raved about him whenever
she could find anyone to listen.
“Of course she wanted to have his photo in her room, but that
was against the rules, so she got around it in this way. Her
grandmother’s picture was in a frame that was suspended between
two little gilt pillars and could be swung over with the back to the
front, so to speak. Sally fastened her Donald’s picture back of her
grandmother’s photo, and when she was all alone in the room, the
boy smiled out at her, but when she heard footsteps in the corridor,
she darted to the mantel and turned it over that her grandmother’s
face might be the one to greet whoever was about to enter. In this
way Sally evaded Miss Snoopins for a long time, but we knew that a
day of reckoning would surely come. Nor were we mistaken.
“We were all in her room on Thanksgiving. Maybe I ought to be
ashamed to confess that, silly as we thought her, we were willing
enough to partake of the spreads that came to her from a doting
mother on any and all holidays. Sally is good-natured and she just
adores me. Not much of a comp, considering her lack of brains, but
anyway when we got a bid to her room for a Thanksgiving spread,
we were all there, Megsy, Babs, Dicky Taylor and the present
speaker. The craziest part of it was that we might have had that
spread early in the evening, with permission, if we had wished, but
that wouldn’t have been romantic enough to suit Sally. She wanted
to wait until the lights-out bell had rung and then, when Miss
Snoopins had passed down the hall, to be sure that the gong had
been obeyed, she wanted us to all steal into her room, which we
did. Sally then locked the door and hung a towel over the keyhole
and drew the rug over the crack at the bottom. We forgot that light
might also shine through the crack at the top. Then Sally lighted her
prized candelabra and set it on the floor in the middle of a big paper
table cloth. Oh, baby, it makes me hungry now to think of that
spread. Say, Babs, do you remember how tender and juicy that
turkey was? Yum! And those cranberries?” Megsy and Barbara
nodded. Virginia smiled. “I’ve read boarding school stories,” she said,
“and there was always some such prank. I suppose that just as the
feast was about to be eaten, there came a knock on the door and—”
But Betsy shook her head. “No, not that soon, thanks be. We had
the turkey devoured even to the bones and were starting on the
dessert, when Sally happened to look up at the mantle. If there
wasn’t the kindly-faced old grandmother smiling down at us. For
once Sally had forgotten to turn it over. Up she sprang and ‘Donald
Dear’ beamed out. Then, to prove just how sentimental she really
was, Sally lighted two tiny candles, one on either side of the frame.
“He certainly was a handsome chap, and we all talked about him
as we ate the delicious pumpkin pie. We asked Sally where she had
met him, how old he was and if she were going to marry him when
she grew up. She said yes indeed, that they were engaged and that
he just adored her. The only reason that he didn’t write to her every
day in the week was because pupils at Vine Haven weren’t allowed
to have letters from boys. Of course we knew that. Now I happened
to remember something which was, that the first time that Sally had
told me about Donald, she had said that he was a class-mate of a
boy cousin and that she had met him at her aunt’s summer home,
but that night she told the girls that she had met Donald at a dance
when she was visiting in Boston. Of course, being the daughter of
the most famous detective that ever was, I noticed that discrepancy,
though none of the other girls did, and I got suspicious at once. If
Sally didn’t know where she had met the handsome Donald (we all
agreed he was that), the question was had she really met him at all?
“However, I didn’t want to spoil the spread by asking any
embarrassing questions, but you know how tickled I was to have
something to detect. Well, I was just eating my last luscious bite of
mince pie when I pricked up an ear, so to speak. ‘Hist!’ I whispered,
holding up one finger. ‘Didst hear a prowler?’ The girls all sprang up
on the alert.
“Of course we expected Miss Snoopins to appear and were
prepared for the worst.”
The narrator paused to be sure that she had properly aroused the
curiosity of her listeners, and then she continued: “There was no
mistaking the fact that there were footfalls without, then a voice
said: ‘Open the door, young ladies, if you please.’ And it wasn’t the
voice of Miss Snoopins. It was no less a personage than Mrs. Martin
who stood there when the door was opened. Sally had at once
darted to the mantel to reverse the picture in the swinging frame,
but we made no attempt to hide the feast. It just couldn’t be done.
My! but weren’t we skeered! We were sure we’d all get our walking
papers, but though Mrs. Martin delivered a short lecture on setting
an example to younger girls, she said kindly: ‘This was absolutely
unnecessary, Sally, for you know I am always perfectly willing to
permit you to share the box of good things that your mother sends
you.’
“Miss Snoopins, who of course had brought Mrs. Martin, stood
back of our beloved principal and she fairly glared at us. One could
plainly see that she was boiling within and more than ever wrathful
because Mrs. Martin was not severe. Suddenly her X-ray glance,
which had been sweeping over the floor with its evidences of guilt,
chanced to fall upon the mantel. Into the room she strode, looking
like a caricature in her flannel nightie, her skimpy kimona and her
flapping bedroom slippers. Never before had her nose looked so long
and peaked or her thin hair so tightly drawn back. When Sally saw
the direction she was taking she looked, and to her horror she
beheld that in her haste she had whirled the picture over twice, and
that Donald dear was again smiling down upon the company.
“Mrs. Martin, having asked us to promise that we would obtain
permission to have a feast, in the future, had retired and so she did
not hear or see what followed. Miss Snoopins’ green eyes fairly
snapped. ‘Sally MacLean, is that a boy’s picture?’ she demanded.
“There being no answer needed, Sally gave none, but she felt like
crying, she said, when the belligerent Buell snatched it from the
back of the frame to which it had been pinned and tore it into
shreds. Even the pieces she thrust into the pocket of her kimona.
‘One hundred buttonholes in garments for the heathen,’ she said in
no quiet voice. In fact, all the girls on our corridor were awakened,
and the first to thrust their heads in at the door were Dora and Cora
Crowell, and weren’t they mad when they saw that we had had a
feast and that they weren’t in on it, but they were all back in their
rooms before Miss Snoopins left which she did after ordering us out
and watching us go.
“Sally said she cried all night. She didn’t care to live without a
picture of her dear Donald. I said her cousin could send her another
picture of his roommate, but she didn’t reply. However, she looked
so sort of queer that I was more than ever sure that she was just
using her imagination.
“Nothing happened until Valentine’s day, and you remember,
Megsy, that Mrs. Martin said that Benjy Wilson might bring over a
few of his friends from the Drexel Military Academy to call and that
one of the teachers, Miss King, if she were free, would act as
chaperone.
“That was a great occasion for the girls. Mrs. Martin excused us
from classes, as the calls were to be in the afternoon and Miss King
took that opportunity to drill us in how to receive visitors. After half
an hour of practice we skipped up to our rooms to get ready. We put
on our prettiest white dresses with gay colored sashes. Margaret and
Babs were to pour chocolate and Sally and I were to pass plates of
wafers. This reception was for all of our sophomore and senior girls.
Of course, Sentimental Sally was more excited than any of the rest
of us, although we were all interested. It was a pleasant break in the
monotony of school life. Eleanor Pettes had a single room at the
front of the house last year, and just as we were all dressed and
waiting for a signal to call us downstairs, Eleanor beckoned and we
flocked to her room. ‘Here they come,’ she whispered, as though
they could hear, ‘and don’t they look handsome, all of them in blue
and gold dress uniforms.’
“They certainly did. There were about fifteen boys walking two by
two with Sergeant Hinkle, one of the seniors, in charge. Sally had
been at her mirror arranging her yellow curls in just the right places,
and so she hadn’t looked out the window, but she was ready a
second later when Miss King appeared to lead us downstairs.
“The boys were standing about in the library looking at the books
on the shelves or pretending to when we entered. Miss King spoke
first with Sergeant Hinkle, and then we were all introduced in a
rather general way, and we stood about talking in groups. I said to
Sally: ‘There are two boys over by the window and they look lonely.
Let’s go and talk with them.’
“‘All right,’ Sally agreed, ‘you lead the way.’
“Sally followed as I wedged through the groups, but when we got
there we found only one boy who stood with his arms folded looking
about the room with rather an amused expression on his really
good-looking face. He turned toward us questioningly for Sally had
uttered a little cry of amazement and had put her hand to her heart.
“Of course, I had recognized the boy at once. He was Donald
Dear! He looked at us pleasantly, even curiously, as he noted Sally’s
very evident agitation, but it was perfectly plain to me that he had
never seen either of us before.
“‘What did Sally say?’ Virginia inquired.
“‘She didn’t say—she bolted! She went up to her room and when
the callers were gone I found her there in tears.’
“‘She said that we’d all think she was a fibber, and that’s what she
really had been, for she hadn’t the least idea who the boy was in the
photograph. She just knew that he was a football player whose
picture was among a lot that her cousin had brought home from
school. She said she was just crazy about him and always would be.’
“‘Did Sally ever see him again?’ Virg inquired.
“‘No, I guess not. Benjy said that Donald Dearing went to France
soon after that to be with his father, who was stationed there.’
“Margaret looked meditatively into the fire. ‘If only girls knew how
much more boys like them when they are not sentimental,’ she said,
‘they would all try to be just good comrades.’
“‘Sally didn’t return to Vine Haven the next term,’ Betsy continued.
‘Honestly, I felt sorry for her, and so I wrote her a Christmas letter
and told her the girls didn’t hold it against her because she had used
her imagination. She was so happy to get that letter and she packed
right up and came back to school.’
“‘Poor girl!’ Virginia said kindly. ‘Do bring her to the meetings of
The Adventure Club. Perhaps it will do her a lot of good. Don’t you
think so, everybody?’
“Babs and Margaret nodded. ‘I always liked Sally, and I’m pretty
sure that she won’t be sentimental again,’ Megsy replied.”
A get-ready-for-bed gong was pealing through the corridors and
the girls arose. “This is Monday,” Babs announced. “I’m going to
study like a good one, so I’ll know every question asked me at the
Saturday Evening Review.”
CHAPTER II
SENTIMENTAL SALLY
Sally MacLean entered Barbara’s room almost shyly on the
following Saturday evening. She was pleased because Betsy had
invited her to attend The Adventure Club’s first gathering, but
remembering her humiliation of the year before, she was not sure
how she would be received.
But the old pupils acted just as though nothing had ever
happened and Virginia welcomed Sally, whom she had not chanced
to meet since her arrival, in her friendliest manner.
“Shall we begin the review at once?” the older girl asked. “Oh,
dear me, no!” Betsy protested. “If this is going to be a club, let’s
elect officers and frame rules, if that’s what it’s called, and choose a
motto an’ everything.”
“I choose to be committee on refreshments,” Babs sang out.
“I choose to be club detective,” Betsy put in.
“I vote for Virginia for president,” Margaret said.
“Second it! Third it! Fourth it!” came a succession of merry voices.
“Winona you may be secretary and I’ll be treasurer if there is to
be anything to treasure.” Margaret happened to glance at the slight
girl who sat somewhat in the shadow.
“Draw your chair into the firelight, Sallykins,” she called pleasantly.
“How can you expect to be elected to an office if you’re out of sight.”
The youngest member drew her chair forward, and when the flood
of light from the student lamp fell upon her doll pretty face and her
long yellow curls that hung to her waist, Virginia, for the first time,
had a real opportunity to observe her.
“Poor girl!” she thought. “She has been too much petted and
pampered by a rich mother, I guess, to develop any real character.
How pretty she would be, with those dark blue eyes and long curling
lashes, if her face wasn’t so weak. Perhaps the club will be able to
help her.”
Virginia’s meditations were interrupted by Margaret, who was
asking, “Every one of us is holding an office except Sally. What can
she be?”
“I choose her for my assistant,” Virg said.
“Whizzle! What an honor! Sal, think of that for dizzy soaring. Up
from the common ranks all in a jiff to vice president.”
Sally flushed, looking prettier than before. “I never do know,
Betsy,” she said feebly, “whether you’re making fun or not.”
Margaret intervened. “Just decide that she always is,” she
suggested. “I never knew Betsy Clossen to be solemn.”
“Then Mistress Megsy, you’re going to have a brand new
experience, for I am going to be solemn five minutes by the clock.”
Turning to Virginia she asked, her expression as big-eyed and
serious as she could make it, “Madame President, we have two
objects for this club, one to study and one to eat. We have each
been appointed to an office of honor. It merely remains now for us
to select a fitting motto.”
Virginia smiled and the other girls laughed, but Betsy looked
reproachfully from one to the other and they could not make her
change her solemn expression. “Everybody think a moment,” Virg
suggested, but almost at once Babs sprang up and clapped her
hands. “I know where there are steens and steens of mottos, any
one of them would do.”
“Where?” Megsy inquired.
“On my motto calendar. I’ll tell you what, Virg. You select a date
and I’ll read the motto that’s under it.”
“Well, then, January fifteenth, which is today.”
Barbara skipped to her bird’s-eye maple writing desk and read
from the small pad calendar.
“Do the work that’s nearest,
Though it’s dull at whiles.
Helping when you meet them,
Lame dogs over stiles.”
Virginia smiled. “That’s excellent,” she said, “and let’s begin to put
it into effect. To do the work that’s nearest, Babs, please hand me
that pile of books yonder and I’ll begin the weekly review.”
“Ooh!” Betsy sank far down in her chair and looked so despondent
that the others laughed. “Let’s get this part over as quickly as ever
we can,” Barbara begged. “I’m almost famished for fudge.”
The review that evening proved two things to the president of the
club. One was that Barbara had really studied during the week that
had just ended and her pretty flushed face and eager way of
answering showed that at last she was really interested in learning.
But when Sally was asked to repeat William Cullen Bryant’s
“Thanatopsis,” the poem that all of the girls in Miss Torrence classes
were required to memorize soon or late, that doll-like little maid
became so confused that Virginia quickly realized that she had no
understanding of what the lines meant.
“Girls,” Virginia said, looking at the others rather than at the
embarrassed newcomer, “there is only one real way to learn poetry, I
think, and that is to first picture what it means. When we thoroughly
understand the sentiment, we can far more easily memorize the
words of the poem.” Then very kindly, “Sally, what picture came to
you when you recited the lines
“To him who in the love of nature holds
Communion with her visible forms, she speaks
A various language; for his gayer hours
She has a voice of gladness and a smile
And eloquence of beauty, and she glides
Into his darker musings with a mild
And healing sympathy that steals away
Their sharpness ere he is aware.”
There was an almost startled expression in the baby-blue eyes
that turned toward the speaker. “Why, I don’t believe I saw any
picture. I was just trying to remember how the words came.”
Margaret spoke. “Virginia,” she said, “those lines always mean one
thing to me. When father died, I felt as though I could not stay in
the house. The very walls oppressed me and so I ran away to a little
woods that we owned and where father and I had often walked after
mother left us. I had been sobbing for hours in my room and it was
late afternoon when I reached the wood. I threw myself down on
the moss near a little fern edged stream and though I cried at first,
the gentle murmur of those great old trees seemed to soothe me
and brought a peace and somehow I felt, that, though I could not
see him, my dear father was still with me. Ever since then I have
loved Thanatopsis and have better understood its meaning.”
“Too, it is true that nature companions our happier moods with
gladness and song,” Virginia said. “Many a time when I have felt
joyous and have galloped on Comrade across the shining desert; the
shout of the wind; the frolicking of the rabbits; the very mountain
peaks seemed to be rejoicing with me. Nature truly is a wonderful
companion.”
Sally was listening with intelligent interest. “Oh, I believe I could
recite it now, Virginia. I think I understand better what it means.”
And she did, no longer afraid.
That ended the review for the evening and Betsy leaped up to
pass the fudge and this time she generously turned the plate so that
Babs would be obliged to take the piece that was nuttiest, it being
nearest her.
That night when Virginia and Winona had returned to their room,
they stood for a few moments, after the lights had been put out, to
gaze toward the ocean, over which hung one burning star that was
much larger than any of the others.
Its path of quivering gold led toward the shore. They had opened
the window and they could hear the murmurous plash of the waves
on the sand, for the tide was out, and the surf was not crashing
against the cliffs.
These two, who so loved and understood nature, were quiet for a
time. Then Winona spoke. “Virg,” she said, “I have felt a strange
stirring within of late. It isn’t discontent, but a soul-voice is urging
me to do something really worthwhile.”
The light had been turned on again and the girls were preparing
for bed.
“What are you planning to do, Winona, that will be more
worthwhile?” Virginia was sure that her Indian friend had not spoken
without giving the matter long and earnest contemplation.
“I do not feel that this school is just the place that I should be.”
Then she hastily continued when she saw an expression of concern
in the face of her dearly loved companion, “I’m not unhappy here,
white Lily, but I seem to know that something else is waiting for me
to do. I shall be ready when it comes.”
They said no more that night as the last “lights-out” bell was
ringing and after that, silence in the rooms was the rule.
Virginia lay awake a long time watching the star that hung like a
lantern in the bit of dark blue of the sky that was framed in her
window. Her thoughts were of Winona. How calm and strong she
was. She would indeed be ready when the call came to do the
worthwhile thing, whatever sacrifice might be required of her.
CHAPTER III
A SECRET ENEMY
“Hist. Virg, hold on a minute!”
The tall slender girl warmly wrapped in hood and long cloak
turned in surprise as she was about to enter the little pine wood,
beyond which lay the cabin of her beloved teacher and friend Miss
Torrence.
She was indeed puzzled when she saw Betsy equally well
protected from the sleet and snow arise from a clump of bushes
near the path.
“How you startled me,” the older girl said, “with that mysterious
sounding ‘Hist’ of yours. Do detectives always do that?”
“I don’t know,” Betsy confessed. “I never did hear my dad say it
and he’s the only detective of my acquaintance.” Then stepping over
a snow bank that she might stand in the shoveled path, she
continued, “I wanted to waylay you. I’ve something to tell you. I
really hate to. It sounds sort of sneaky, but we of The Adventure
Club have just got to stand together and protect each other, haven’t
we, Madame President?”
“Why, yes. I think we should. What have you heard?”
“Well, I didn’t have much of anything to do this morning, being as
it’s Saturday and I thought I’d go up to the Tower Room that’s been
vacant since Gwendolyn Laureat went away before Christmas. I
never will know why I stole up those stairs as quietly as ever I could,
unless it’s because sleuths in the movies always do steal about that
way. When I got to the top of the stairs, I saw that the door was
closed. There was nothing particularly strange about that, but, just
as I had my hand on the knob to turn it, I heard voices inside. I tell
you, it gave me a start! I remembered all the stories about that
room being haunted and I was just about to dart away when I
recognized one of the voices. The speaker stood so close to the door
I could hear what she said. It was Kathryn Von Wellering and from
what she was saying I knew that she is your enemy.”
“My enemy?” Virginia exclaimed in surprise. “Why, what have I
done to make Miss Von Wellering dislike me? All of the girls in that
‘Exclusive Three’ group have failed to know that I exist.”
Betsy looked wise. “Don’t you remember that your story was
voted first place in last term’s contest and that her story came out
third? She had boasted about among her set that she would be the
next Editress of The Manuscript Magazine and she isn’t used to not
having what she wants.”
“Oh, that’s it. But what can she do?”
“What I heard her say was that she was going to see to it that the
first copy of the magazine was such a failure that Miss Torrence
would gladly appoint her as Editor.”
Virginia looked troubled. “I’m truly sorry about this. I never did
want the position and if Miss Von Wellering really wants it, I shall be
glad to give it to her.”
“Well, you’ll freeze, Virg, if I keep you standing out in this
snowstorm any longer, but I just want to tell you that I heard one of
the three say that you would find, at the last minute, that your own
story was the only usable contribution that you would receive.”
“Why, that can’t be possible. Miss Torrence told me this very
morning that she would have a short story by Anne Peterson and a
poem by Belle Wiley to give me before the Manuscript Magazine is
made up.”
“It certainly is too bad that Eleanor Pettes decided to go to college
prep this term instead of coming here,” Virginia sighed. “She would
know just what to do.” Then, brightly, “But I must hurry along. It
was lucky that I started earlier than usual for Pine Cabin or I would
be dolefully late.”
“I’ll keep my eyes and ears open,” Betsy promised as she began
to walk backwards toward the school. “But don’t give up the ship,
Virg. Stick at your post and we’ll back you. Whizzle, I’ll write a story
myself or a poem, even, if you run short of material.” Then, turning,
she started to run, while Virginia continued on her way smiling, as
she thought of what the Manuscript Magazine would be, if Betsy
Clossen tried to write for it. Betsy’s forte most certainly was not
composition.
When Virg entered the Pine Cabin whither she had gone alone to
discuss the first edition of The Monthly Magazine, which had been
Miss Torrence’s pet hobby since she first began to teach at Vine
Haven, the girl noted a perplexed expression in the eyes of her
friend and teacher as she looked up from her desk that was
scattered over with papers.
“Virginia,” Miss Torrence began at once, “I cannot understand in
the least what has happened. The story and poem that have been
handed in by Anne Petersen and Belle Wiley are not fit to use. They
never before did such poor work. In fact, these contributions do not
sound at all like their style of composition. I was particularly anxious
to have our January Manuscript Magazine an excellent one as Dean
Craig of the Drexel Academy was asking me about the plan and
requested that he might see our January number. He may start a
similar magazine in his English classes. We surely can’t use work as
poor as this and there remains but one week in which to find a really
excellent short story. Kathryn Von Wellering has withdrawn her story
saying that it cannot be used unless she is given the position of
editor.”
“I’d be glad to let her have it,” Virg said, but Miss Torrence shook
her head. “Character as well as literary ability are taken into
consideration when we appoint a girl at Vine Haven to a post of
honor, and Kathryn’s influence is not of the best. Well, we have a
week to try to unearth a worthwhile story.” Virginia soon left,
wondering where a story was to be found. Virg thought often that
snowy Saturday about what both Miss Torrence and Betsy Clossen
had told her. It was hard to believe that she had a real enemy, she
who had befriended everything that lived and who felt kindly toward
all.
“Virg, I believe that you actually would give up the post of honor
that you have won,” Margaret declared that evening as she prepared
for a second meeting of The Adventure Club.
“Why not?” the girl addressed glanced up brightly. “It was an
honor thrust upon me, not one that I coveted. It isn’t bringing me
any great happiness and it has brought me an enemy. Who will, may
have it, or, I mean, could-if it were within my power to dispose of it,
but Miss Torrence has expressed her desire that I retain the position
whether or not we receive contributions considered worthy of
acceptance.”
“Betsy declares that she is going to submit a poem.” This from
Sally who was less timid than she had been at a previous meeting.
Then she tittered in a way which made her seem even more foolish
than she really was. “That’s why she’s late. She’s sitting curled up in
our room writing it now.”
“The Fates deliver us from any poetry that Betsy might write,”
Margaret had just said when there came a pounding on the door,
and, clad in her cherry-red bath robe, the object of their
conversation burst into the room waving a sheet of foolscap paper.
“It’s done! The day is saved. Never before will there have been an
edition of The Manuscript Magazine to contain a literary gem like
this.”
The other members of the study club looked at each other in
mock despair. “Must we endure the torture?” Babs moaned.
“Get it over with as soon as you possibly can, if it must be done,”
Margaret pleaded.
Virginia interposed. “Girls, how dreadful of you! It might be good.”
Betsy solemnly bowed, her hand on her heart. “Lady, I thank you
for them kind words,” she said. Then looking about the room, she
inquired, “Where’ll be the most effective place to stand?”
“I’d keep real close to the door if I were you,” Barbara suggested.
“Thanks, I will, though I won’t mind at all if you do pelt me with
fudge.”
“Indeed, not a piece shall you get unless your poetry pleases us,”
threatened Margaret.
Babs hastened to add, “I choose Betsy’s portion for it’s a foregone
conclusion that she won’t get any.”
“Silence, young ladies, IF you please.” This in exact imitation of
Miss King’s voice and manner. Then making another elaborate bow,
Betsy began to read:
“There is a young lady named Virg.
Who said Life is surely a scourge.
I’m so witty and wise
That I must editrize
Though I’d heaps rather be hearing my dirge.”
The listeners laughed while Babs clapped with her thumbnails
only.
“There’s a senorita, named Marguerita
And Oh-a but she’s vera sweeta.
Her prida brought to her a fall
Once in a thronged study hall.
Her prida were her high-heeled feet-a.
There is a young damsel named Babs
With manners most shocking.
She grabs!
Whenever there’s candy
That’s anywhere handy,
The nuttiest pieces she nabs.
There is a fair maiden named Sally
Who lives in our Sweet Pickle Alley.
In front of a mirror
You oftenest see her
Whenever she has time to dally.
There is a most witty young poet
Named Betsy, and I’m sure you know it.
She can tell by your glances,
As you listen in trances,
With a bouquet, just waiting to throw it.”
Betsy ducked just in time for soft pillows snatched from the
window seat were hurled at her. Laughingly she gathered them up
and replaced them in a prim row, then she sank down among them
as though exhausted. “Believe me, that’s the hardest work I’ve done
in my short lifetime. I’d heaps rather shovel coal for a living. I
thought I could never think of a word to rhyme with Sally. Luckily we
call our corridor Sweet Pickle Alley. That helped some!” Then she
interrupted herself to point an accusing finger. “Quick! Look! Caught
in the act. Wasn’t I right about Babs? It isn’t yet time to pass the
fudge and there she is helping herself to the very piece that I had
intended to take, because it’s so bulging full of nuts.” Barbara sprang
up, passed the plate and insisted that Betsy take the nutty piece.
Then, as they munched, Margaret said, “I’ll never forget the day I
wore those high-heeled slippers. Wasn’t I embarrassed, it being a
reception for patrons and parents? Common sense heels for me.”
The president of The Adventure Club tapped upon the table with
her pencil. “Attention, if you please, young ladies,” she said, “there is
a matter of importance to be discussed.”
The girls looked up wonderingly. “Can you all keep a secret?” Virg
asked mysteriously.
“Why, of course we can.” This protestingly from Margaret.
“Whizzle, what a kweestion? A bottomless well couldn’t be more
secretive than I am if I give my word.” Betsy held up her right hand
as though taking a vow.
“It won’t be hard for me to keep it if I can talk it over with you
girls,” Barbara told them. To the surprise of the others Sally rose.
“I’d rather not try,” she said, speaking more seriously than usual.
“If it leaks out, you’d be sure to think I told, so, if you’ll excuse me,
I’d rather not know it.”
Virginia rose and placing an arm about the slender girl who had
her hand on the door knob, she led her back to the group. “Sally,”
she said kindly, “I am sure that you will keep this secret.”
The pretty face of the youngest girl glowed with happiness and
pride. It was the first time since she had been in that seminary that
someone had expressed faith in her. Many a time she had seen
groups of girls stop their chattering when she neared and she had
felt left out. “They think I’d tell what they’re saying, I suppose,” had
been her unhappy conclusion, as she wandered away by herself
feeling so alone and unwanted. But this wonderful girl, who was not
only president of this little club but also editor of The Manuscript
Magazine, actually wanted her to stay and share a real secret. Sally
vowed within herself that Virginia would find her worthy of the trust.
“We’re all bristling with curiosity, as a porcupine was heard to
remark,” Betsy said. “What kind of a secret is it?”
Virginia smiled at the mischievous would-be detective, as she
replied: “It isn’t anything that will interest you greatly. Yesterday
Mrs. Martin sent for me and asked if we girls from the West knew
someone who would appreciate a term at Vine Haven as guest. Now
that Gwendolyn Laureat has gone, the Tower Room is vacant. I do
not know of anyone, but I said that I would ask my closest friends if
she wished. Mrs. Martin agreed, but requested that we tell no one
else as she never wished the identity of the guest pupil to be
generally known.”
The girls were silent for a moment thinking over their friends and
acquaintances but finally they shook their heads. “It’s just too bad,”
Margaret said, “I’m ever so sure there must be some talented girl
who would love to have the advantages that this school offers and
—”
“Such as the refining influence of the members of The Adventure
Club,” put in Betsy with a twinkle. “I’ll undertake teaching her up-to-
the-minute slang.”
Megsy, not heeding the interruption, continued, “and if The
Exclusive Three did not know her identity, she ought to be very
happy here.”
“Woe to her if they do find it out,” Barbara commented. “She
might as well pack up and leave that very day.”
“Well, since there is no one whom we can suggest, we ourselves
will not know who the guest pupil is, as, of course, Mrs. Martin has
many sources to draw upon. Boston is full of girls, poor, but
talented.”
“Now, let’s have our weekly lesson review.” Virginia picked up an
Ancient History and in the midst of moans and groans asked the first
question.
“Babs, you’re improving by the minute,” was Margaret’s comment
when the get-ready-for-bed gong pealed through the corridors.
“Thanks, greatly! I mean to be a ‘Shining Light’ on the spring
exams.”
“Wouldn’t you faint right on the spot if you ever saw your name
on the Honor Roll board down in the main corridor?” Megsy asked.
“Would she? I’ll tell the world!” Betsy answered for her. Then
teasingly, “Honestly girls, you may find this hard to believe but I
actually saw Babs stop in front of that popular black board every day
last week to see if her name is there yet.”
Barbara flushed but spunkily protested, “I don’t care if I did. Now
that Virg and Margaret are on it, I mean to be, too, if I possibly can.”
“Well, you needn’t bite my head off. Sally and I wouldn’t be on it,
if we could.”
Then Sally surprised them all by saying, “Now that Virginia’s name
is there, I’d like ever so much to get my name on it, too.”
“How’s that for idolatry?” Betsy began to tease, but Virginia
remarked seriously, “Sally, your hardest subject seems to be algebra.
I’ll help you, if you wish to study after hours just as Miss Torrence
helps me.”
“Whee-gee!” Betsy whistled. “If Sally MacLean gets her name on
the Honor Roll, it’s me as will faint and I don’t think I’ll ever come
to.”
When the girls were gone, and the lights had been turned out,
Margaret exclaimed, “Oh, Virg, see how beautiful the snowy world is
in the moonlight. I’m so glad that Monday is a holiday. Let’s go for a
hike if Mrs. Martin will permit. I just adore wading through snow-
drifts.”
“That would be a great adventure and a new one for me,” said the
girl from the desert where snow-drifts are unknown. They were
indeed to have an adventure.
CHAPTER IV
THE FIRST ADVENTURE
“A whole holiday and every hour of it free. I feel like some caged
bird let loose,” Margaret exclaimed as the five girls from Vine Haven
Seminary started away from the school. All were clad in their
warmest coats, with leggings, mittens and flying scarfs to match the
bright tams that perched jauntily atop of their heads.
“And to think that we may hike wherever we wish, on only one
condition, and that to report to Mrs. Martin half an hour before
lunch,” Barbara chattered.
Virginia laughed. “One might think it the greatest kind of a lark
just to go outside of the gate,” she said. “I can understand it now,
but when I remember how I have galloped all over the desert for
miles without thought of keeping within certain boundaries, I don’t
wonder that we feel like caged birds.”
“Snow birds, then,” Betsy’s merry face beamed out from beneath
her cherry colored tam. “Sally surely is. I just adore those white furs.
You look like a princess, Sal, stepped out of a fairy book with your
golden curls hanging like a mantle about your shoulders.”
The others laughed. “Betsy, you aren’t going to burst out into
poetry again, are you?”
“Not guilty!” that merry maid replied. Then pausing to look about
she inquired. “Which way shall we go in search of adventure? Behind
us is the sea. The wind is too icily cold to go in that direction. Down
below us is the village and beyond that—what?”
“Let’s go and find out. Have we time?” Margaret consulted her
wrist watch.
“Time to burn,” she announced. “It’s only eight-thirty. I’ve walked
to the village in half an hour often.”
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookgate.com

More Related Content

Similar to Python pocket reference 5ed. Edition Mark Lutz (20)

PDF
REPORT ON AUDIT COURSE PYTHON BY SANA 2.pdf
Sana Khan
 
PPTX
Chapter 2: Basics of programming pyton programming
biniyamtiktok
 
PDF
Mastering the Interview: 50 Common Interview Questions Demystified
MalcolmDupri
 
PDF
Introduction-To-Python- a guide to master
ImadM4
 
PPTX
Python Mastery: A Comprehensive Guide to Setting Up Your Development Environment
Python Devloper
 
PPTX
Session-1_Introduction to Python.pptx
WajidAliHashmi2
 
PPTX
2024-25 TYBSC(CS)-PYTHON_PROG_ControlStructure.pptx
sangeeta borde
 
PPTX
Python final presentation kirti ppt1
Kirti Verma
 
DOCX
Seminar report On Python
Shivam Gupta
 
PDF
Unit 1-Part-1-Introduction to Python.pdf
Harsha Patil
 
PPT
It covers the various basics and fundamentals aspect of Python Programing
ssuserc607cd
 
DOCX
Seminar report on python 3 course
HimanshuPanwar38
 
PPTX
Python Demo.pptx
ParveenShaik21
 
PPTX
UNIT 1 PYTHON introduction and basic level
vasankarponnapalli2
 
PPTX
Python Demo.pptx
ParveenShaik21
 
PDF
[FREE PDF sample] Programming Python with CD 2nd Edition Mark Lutz ebooks
raginmoradtx
 
PDF
05 python.pdf
SugumarSarDurai
 
PPT
1-ppt-python.ppt
ssusera99a83
 
PDF
python-handbook.pdf
RaviKumar76265
 
PPTX
Introduction-to-Python-Programming1.pptx
vijayalakshmi257551
 
REPORT ON AUDIT COURSE PYTHON BY SANA 2.pdf
Sana Khan
 
Chapter 2: Basics of programming pyton programming
biniyamtiktok
 
Mastering the Interview: 50 Common Interview Questions Demystified
MalcolmDupri
 
Introduction-To-Python- a guide to master
ImadM4
 
Python Mastery: A Comprehensive Guide to Setting Up Your Development Environment
Python Devloper
 
Session-1_Introduction to Python.pptx
WajidAliHashmi2
 
2024-25 TYBSC(CS)-PYTHON_PROG_ControlStructure.pptx
sangeeta borde
 
Python final presentation kirti ppt1
Kirti Verma
 
Seminar report On Python
Shivam Gupta
 
Unit 1-Part-1-Introduction to Python.pdf
Harsha Patil
 
It covers the various basics and fundamentals aspect of Python Programing
ssuserc607cd
 
Seminar report on python 3 course
HimanshuPanwar38
 
Python Demo.pptx
ParveenShaik21
 
UNIT 1 PYTHON introduction and basic level
vasankarponnapalli2
 
Python Demo.pptx
ParveenShaik21
 
[FREE PDF sample] Programming Python with CD 2nd Edition Mark Lutz ebooks
raginmoradtx
 
05 python.pdf
SugumarSarDurai
 
1-ppt-python.ppt
ssusera99a83
 
python-handbook.pdf
RaviKumar76265
 
Introduction-to-Python-Programming1.pptx
vijayalakshmi257551
 

Recently uploaded (20)

PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPSX
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
PPTX
Pyhton with Mysql to perform CRUD operations.pptx
Ramakrishna Reddy Bijjam
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PDF
Federal dollars withheld by district, charter, grant recipient
Mebane Rash
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
DOCX
A summary of SPRING SILKWORMS by Mao Dun.docx
maryjosie1
 
PDF
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
PDF
Zoology (Animal Physiology) practical Manual
raviralanaresh2
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PPTX
How to Configure Prepayments in Odoo 18 Sales
Celine George
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PDF
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
PPTX
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PPTX
Capitol Doctoral Presentation -July 2025.pptx
CapitolTechU
 
PDF
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
Pyhton with Mysql to perform CRUD operations.pptx
Ramakrishna Reddy Bijjam
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
Federal dollars withheld by district, charter, grant recipient
Mebane Rash
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
A summary of SPRING SILKWORMS by Mao Dun.docx
maryjosie1
 
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
Zoology (Animal Physiology) practical Manual
raviralanaresh2
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
How to Configure Prepayments in Odoo 18 Sales
Celine George
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
Capitol Doctoral Presentation -July 2025.pptx
CapitolTechU
 
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
Ad

Python pocket reference 5ed. Edition Mark Lutz

  • 1. Instant Ebook Access, One Click Away – Begin at ebookgate.com Python pocket reference 5ed. Edition Mark Lutz https://ebookgate.com/product/python-pocket-reference-5ed- edition-mark-lutz/ OR CLICK BUTTON DOWLOAD EBOOK Get Instant Ebook Downloads – Browse at https://ebookgate.com Click here to visit ebookgate.com and download ebook now
  • 2. Instant digital products (PDF, ePub, MOBI) available Download now and explore formats that suit you... Programming Python 3rd ed Edition Mark Lutz https://ebookgate.com/product/programming-python-3rd-ed-edition-mark- lutz/ ebookgate.com Learning Python 2nd ed Edition Mark Lutz https://ebookgate.com/product/learning-python-2nd-ed-edition-mark- lutz/ ebookgate.com grep Pocket Reference A Quick Pocket Reference for a Utility Every Unix User Needs Pocket Reference O Reilly 1st Edition Bambenek https://ebookgate.com/product/grep-pocket-reference-a-quick-pocket- reference-for-a-utility-every-unix-user-needs-pocket-reference-o- reilly-1st-edition-bambenek/ ebookgate.com JavaScript Pocket Reference 2nd Edition Flanagan https://ebookgate.com/product/javascript-pocket-reference-2nd-edition- flanagan/ ebookgate.com
  • 3. Engineers Precision Data Pocket Reference Heather https://ebookgate.com/product/engineers-precision-data-pocket- reference-heather/ ebookgate.com Python Essential Reference 3rd Edition Beazley https://ebookgate.com/product/python-essential-reference-3rd-edition- beazley/ ebookgate.com C Pocket Reference 1st Edition Peter Prinz https://ebookgate.com/product/c-pocket-reference-1st-edition-peter- prinz/ ebookgate.com Windows PowerShell pocket reference 2nd Edition Lee Holmes https://ebookgate.com/product/windows-powershell-pocket-reference-2nd- edition-lee-holmes/ ebookgate.com CSS Pocket Reference 5th Edition Eric A. Meyer https://ebookgate.com/product/css-pocket-reference-5th-edition-eric-a- meyer/ ebookgate.com
  • 8. Python Pocket Reference, Fifth Edition by Mark Lutz Copyright © 2014 Mark Lutz. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebasto‐ pol, CA 95472. O’Reillybooksmaybepurchasedforeducational,business,orsalespromotional use. Online editions are also available for most titles (http://my.safaribookson line.com). For more information, contact our corporate/institutional sales de‐ partment: 800-998-9938 or [email protected]. Editor: Rachel Roumeliotis Production Editor: Kristen Brown Copyeditor: Richard Carey Proofreader: Amanda Kersey Indexer: Lucie Haskins Cover Designer: Randy Comer Interior Designer: David Futato October 1998: First Edition January 2002: Second Edition February 2005: Third Edition October 2009: Fourth Edition February 2014: Fifth Edition Revision History for the Fifth Edition: 2014-01-17: First release See http://oreilly.com/catalog/errata.csp?isbn=9781449357016 for release de‐ tails. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Python Pocket Reference, the im‐ age of a rock python, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. ISBN: 978-1-449-35701-6 [M]
  • 9. Table of Contents Introduction 1 Book Conventions 2 Python Command-Line Usage 3 Python Command Options 4 Command-Line Program Specification 5 Python 2.X Command Options 7 Python Environment Variables 7 Operational Variables 8 Python Command Option Variables 9 Python Windows Launcher Usage 10 Launcher File Directives 10 Launcher Command Lines 11 Launcher Environment Variables 11 Built-in Types and Operators 12 Operators and Precedence 12 Operator Usage Notes 14 Operations by Category 16 Sequence Operation Notes 20 Specific Built-in Types 21 Numbers 22 iii
  • 10. Strings 24 Unicode Strings 42 Lists 46 Dictionaries 53 Tuples 57 Files 58 Sets 63 Other Types and Conversions 65 Statements and Syntax 67 Syntax Rules 67 Name Rules 69 Specific Statements 71 The Assignment Statement 72 The Expression Statement 76 The print Statement 77 The if Statement 80 The while Statement 80 The for Statement 80 The pass Statement 81 The break Statement 81 The continue Statement 81 The del Statement 81 The def Statement 82 The return Statement 86 The yield Statement 87 The global Statement 88 The nonlocal Statement 89 The import Statement 89 The from Statement 93 The class Statement 95 The try Statement 97 The raise Statement 99 iv | Table of Contents
  • 11. The assert Statement 101 The with Statement 102 Python 2.X Statements 104 Namespace and Scope Rules 105 Qualified Names: Object Namespaces 105 Unqualified Names: Lexical Scopes 105 Nested Scopes and Closures 107 Object-Oriented Programming 108 Classes and Instances 109 Pseudoprivate Attributes 110 New-Style Classes 111 Formal Inheritance Rules 112 Operator Overloading Methods 117 Methods for All Types 118 Methods for Collections (Sequences, Mappings) 123 Methods for Numbers (Binary Operators) 125 Methods for Numbers (Other Operations) 128 Methods for Descriptors 129 Methods for Context Managers 130 Python 2.X Operator Overloading Methods 131 Built-in Functions 134 Python 2.X Built-in Functions 155 Built-in Exceptions 161 Superclasses: Categories 162 Specific Exceptions 163 Specific OSError Exceptions 167 Warning Category Exceptions 169 Warnings Framework 170 Python 3.2 Built-in Exceptions 171 Python 2.X Built-in Exceptions 172 Built-in Attributes 172 Standard Library Modules 173 Table of Contents | v
  • 12. The sys Module 174 The string Module 182 Functions and Classes 182 Constants 183 The os System Module 184 Administrative Tools 185 Portability Constants 186 Shell Commands 187 Environment Tools 189 File Descriptor Tools 190 File Pathname Tools 193 Process Control 197 The os.path Module 200 The re Pattern-Matching Module 202 Module Functions 202 Regular Expression Objects 205 Match Objects 205 Pattern Syntax 207 Object Persistence Modules 210 The shelve and dbm Modules 211 The pickle Module 213 The tkinter GUI Module and Tools 216 tkinter Example 216 tkinter Core Widgets 217 Common Dialog Calls 218 Additional tkinter Classes and Tools 219 Tcl/Tk-to-Python/tkinter Mappings 220 Internet Modules and Tools 221 Other Standard Library Modules 224 The math Module 224 The time Module 225 The timeit Module 226 vi | Table of Contents
  • 13. The datetime Module 227 The random Module 228 The json Module 228 The subprocess Module 229 The enum Module 229 The struct Module 230 Threading Modules 231 Python SQL Database API 232 API Usage Example 233 Module Interface 234 Connection Objects 234 Cursor Objects 235 Type Objects and Constructors 236 More Hints and Idioms 236 Core Language Hints 237 Environment Hints 238 Usage Hints 240 Assorted Hints 242 Index 243 Table of Contents | vii
  • 15. Python Pocket Reference Introduction Python is a general-purpose, multiparadigm, open source com‐ puter programming language, with support for object-oriented, functional, and procedural coding structures. It is commonly used both for standalone programs and for scripting applications in a wide variety of domains, and is generally considered to be one of the most widely used programming languages in the world. AmongPython’sfeaturesareanemphasisoncodereadabilityand library functionality, and a design that optimizes developer pro‐ ductivity, software quality, program portability, and component integration.Pythonprogramsrunonmostplatformsincommon use, including Unix and Linux, Windows and Macintosh, Java and .NET, Android and iOS, and more. This pocket reference summarizes Python types and statements, special method names, built-in functions and exceptions, com‐ monly used standard library modules, and other prominent Python tools. It is intended to serve as a concise reference tool for developers and is designed to be a companion to other books that provide tutorials, code examples, and other learning materials. This fifth edition covers both Python 3.X and 2.X. It focuses pri‐ marily on 3.X, but also documents differences in 2.X along the 1
  • 16. way. Specifically, this edition has been updated to be current with Python versions 3.3 and 2.7 as well as prominent enhancements in the imminent 3.4 release, although most of its content also appliesbothtoearlierandtolaterreleasesinthe3.Xand2.Xlines. This edition also applies to all major implementations of Python —including CPython, PyPy, Jython, IronPython, and Stackless —and has been updated and expanded for recent changes in lan‐ guage, libraries, and practice. Its changes include new coverage of the MRO and super(); formal algorithms of inheritance, im‐ ports, context managers, and block indentation; and commonly used library modules and tools, including json, timeit, random, subprocess, enum, and the new Windows launcher. Book Conventions The following notational conventions are used in this book: [] In syntax formats, items in brackets are optional; brackets are also used literally in some parts of Python’s syntax as noted where applicable (e.g., lists). * In syntax formats, items followed by an asterisk can be re‐ peated zero or more times; star is also used literally in some parts of Python’s syntax (e.g., multiplication). a | b In syntax formats, items separated by a bar are alternatives; barisalsousedliterallyinsomepartsofPython’ssyntax(e.g., union). Italic Used for filenames and URLs, and to highlight new or im‐ portant terms. Constant width Used for code, commands, and command-line options, and toindicatethenamesofmodules,functions,attributes,vari‐ ables, and methods. 2 | Python Pocket Reference
  • 17. Constant width italic Used for replaceable parameter names in the syntax of com‐ mand lines, expressions, functions, and methods. Function() Except where noted, callable functions and methods are de‐ noted by trailing parentheses, to distinguish them from oth‐ er types of attributes. See “Section Header Name” Referencestoothersectionsinthisbookaregivenbysection header text in double quotes. NOTE In this book, “3.X” and “2.X” mean that a topic applies to all commonly used releases in a Python line. More specific release numbers are used for topics of more limited scope (e.g., “2.7” means 2.7 only). Because future Python changes can invalidate applicability to future releases, also see Python’s “What’s New” documents, currently maintained at http://docs.python.org/3/whatsnew/index.html for Pythons released after this book. Python Command-Line Usage Command lines used to launch Python programs from a system shell have the following format: python [option*] [ scriptfile | -c command | -m module | - ] [arg*] In this format, python denotes the Python interpreter executable with either a full directory path, or the word python that is re‐ solved by the system shell (e.g., via PATH settings). Command-line options intended for Python itself appear before the specification of the program code to be run (option). Arguments intended for the code to be run appear after the program specification (arg). Python Command-Line Usage | 3
  • 18. Python Command Options The option items in Python command lines are used by Python itself, and can be any of the following in Python 3.X (see “Python 2.X Command Options” ahead for 2.X differences): -b Issue warnings for calling str() with a bytes or bytearray object and no encoding argument, and comparing a bytes or bytearray with a str. Option -bb issues errors instead. -B Do not write .pyc or .pyo byte-code files on imports. -d Turn on parser debugging output (for developers of the Python core). -E IgnorePythonenvironmentvariablesdescribedahead(such as PYTHONPATH). -h Print help message and exit. -i Enter interactive mode after executing a script. Hint: useful for postmortem debugging; see also pdb.pm(), described in Python’s library manuals. -O Optimizegeneratedbytecode(createanduse.pyobyte-code files). Currently yields a minor performance improvement. -OO Operates like -O, the previous option, but also removes docstrings from byte code. -q Do not print version and copyright message on interactive startup (as of Python 3.2). 4 | Python Pocket Reference
  • 19. -s Do not add the user site directory to the sys.path module search path. -S Do not imply “import site” on initialization. -u Force stdout and stderr to be unbuffered and binary. -v Print a message each time a module is initialized, showing the place from which it is loaded; repeat this flag for more verbose output. -V Print Python version number and exit (also available as --version). -W arg Warnings control: arg takes the form action:message: category:module:lineno. See also “Warnings Framework” and “Warning Category Exceptions” ahead, and the warn ings module documentation in the Python Library Refer‐ ence manual (available at http://www.python.org/doc/). -x Skip first line of source, allowing use of non-Unix forms of #!cmd. -X option Set implementation-specific option (as of Python 3.2); see implementation documentation for supported option values. Command-Line Program Specification Code to be run and command-line arguments to send to it are specified in the following ways in Python command lines: Python Command-Line Usage | 5
  • 20. scriptfile Denotes the name of a Python script file to run as the main, topmostfileofaprogram(e.g.,python main.py runsthecode in main.py). The script’s name may be an absolute or relative (to “.”) filename path, and is made available in sys.argv[0]. On some platforms, command lines may also omit the python component if they begin with a script file name and have no options for Python itself. -c command Specifies Python code (as a string) to run (e.g., python -c "print('spam' * 8)" runs a Python print operation). sys.argv[0] is set to '-c'. -m module Runs a module as a script: searches for module on sys.path and runs it as a top-level file (e.g., python -m pdb s.py runs the Python debugger module pdb located in a standard li‐ brary directory, with argument s.py). module may also name a package (e.g., idlelib.idle). sys.argv[0] is set to the module’s full path name. − Reads Python commands from the standard input stream, stdin (the default); enters interactive mode if stdin is a “tty” (interactive device). sys.argv[0] is set to '−'. arg* Indicates that anything else on the command line is passed to the script file or command, and appears in the built-in list of strings sys.argv[1:]. If no scriptfile, command, or module is given, Python enters in‐ teractive mode, reading commands from stdin (and using GNU readline for input, if installed), and setting sys.argv[0] to '' (the empty string) unless invoked with option – in the preceding list. Besides using traditional command lines at a system shell prompt, you can also generally start Python programs by clicking their filenames in a file explorer GUI; by calling functions in the 6 | Python Pocket Reference
  • 21. Python standard library (e.g., os.popen()); by using program- launch menu options in IDEs such as IDLE, Komodo, Eclipse, and NetBeans; and so on. Python 2.X Command Options Python 2.X supports the same command-line format, but does not support the -b option, which is related to Python 3.X’s string typechanges,northerecent–qand–Xadditionsin3.X.Itsupports additional options in 2.6 and 2.7 (some may be present earlier): -t and -tt Issues warnings for inconsistent mixtures of tabs and spaces in indentation. Option -tt issues errors instead. Python 3.X alwaystreatssuchmixturesassyntaxerrors(seealso“Syntax Rules”). -Q Division-related options: -Qold (the default), -Qwarn, -Qwarnall, and –Qnew. These are subsumed by the new true division behavior of Python 3.X (see also “Operator Usage Notes”). -3 Issues warnings about any Python 3.X incompatibilities in code that the Python standard installation’s 2to3 tool cannot trivially fix. -R Enables a pseudorandom salt to make hash values of various types be unpredictable between separate invocations of the interpreter, as a defense against denial-of-service attacks. New in Python 2.6.8. This switch is also present in 3.X as of 3.2.3 for compatibility, but this hash randomization is en‐ abled by default as of 3.3. Python Environment Variables Environment (a.k.a. shell) variables are systemwide settings that span programs and are used for global configuration. Python Environment Variables | 7
  • 22. Operational Variables The following are major user-configurable environment vari‐ ables related to script behavior: PYTHONPATH Augments the default search path for imported module files. The format of this variable’s value is the same as the shell’s PATH setting: directory pathnames separated by colons (semicolons on Windows). If set, module imports search for imported files or directories in each directory listed in PYTHONPATH, from left to right. Merged into sys.path—the fullmodulesearchpathforleftmostcomponentsinabsolute imports—after the script’s directory, and before standard li‐ brary directories. See also sys.path in “The sys Module”, and “The import Statement”. PYTHONSTARTUP If set to the name of a readable file, the Python commands in that file are executed before the first prompt is displayed in interactive mode (useful to define often-used tools). PYTHONHOME If set, the value is used as an alternate prefix directory for library modules (or sys.prefix, sys.exec_prefix). The de‐ fault module search path uses sys.prefix/lib. PYTHONCASEOK If set, filename case is ignored in import statements (cur‐ rently only on Windows and OS X). PYTHONIOENCODING Assign to string encodingname[:errorhandler] to override the default Unicode encoding (and optional error handler) used for text transfers made to the stdin, stdout, and stderr streams. This setting may be required for non-ASCII text in some shells (e.g., try setting this to utf8 or other if prints fail). 8 | Python Pocket Reference
  • 23. PYTHONHASHSEED If set to “random”, a random value is used to seed the hashes of str, bytes, and datetime objects; may also be set to an integerintherange0...4,294,967,295 togethashvalueswith a predictable seed (as of Python 3.2.3 and 2.6.8). PYTHONFAULTHANDLER If set, Python registers handlers at startup to dump a trace‐ back on fatal signal errors (as of Python 3.3, and equivalent to -X faulthandler). Python Command Option Variables The following environment variables are synonymous with some of Python’s command-line options (see “Python Command Op‐ tions”): PYTHONDEBUG If nonempty, same as -d option. PYTHONDONTWRITEBYTECODE If nonempty, same as -B option. PYTHONINSPECT If nonempty, same as -i option. PYTHONNOUSERSITE If nonempty, same as -s option. PYTHONOPTIMIZE If nonempty, same as -O option. PYTHONUNBUFFERED If nonempty, same as -u option. PYTHONVERBOSE If nonempty, same as -v option. PYTHONWARNINGS If nonempty, same as -W option, with same value. Also ac‐ cepts a comma-separated string as equivalent to multiple -W options. (As of Python 3.2 and 2.7.) Python Environment Variables | 9
  • 24. Python Windows Launcher Usage OnWindows(only),Python3.3andlaterinstallascriptlauncher, also available separately for earlier versions. This launcher con‐ sists of the executables py.exe (console) and pyw.exe (noncon‐ sole), which can be invoked without PATH settings; are registered to run Python files via filename associations; and allow Python versions to be selected in three ways—with “#!” Unix-like direc‐ tives at the top of scripts, with command-line arguments, and with configurable defaults. Launcher File Directives The launcher recognizes “#!” lines at the top of script files that name Python versions in one of the following forms, in which * is either: empty to use the default version (currently 2 if installed and similar to omitting a “#!” line); a major version number (e.g., 3) to launch the latest version in that line installed; or a com‐ plete major.minor specification, optionally suffixed by −32 to pre‐ fer a 32-bit install (e.g., 3.1–32): #!/usr/bin/env python* #!/usr/bin/python* #!/usr/local/bin/python* #!python* Any Python (python.exe) arguments may be given at the end of the line, and Python 3.4 and later may consult PATH for “#!” lines that give just python with no explicit version number. 10 | Python Pocket Reference
  • 25. Launcher Command Lines The launcher may also be invoked from a system shell with com‐ mand lines of the following form: py [pyarg] [pythonarg*] script.py [scriptarg*] More generally, anything that may appear in a python command after its python component may also appear after the optional pyarg in a py command, and is passed on to the spawned Python verbatim. This includes the -m, -c, and - program specification forms; see “Python Command-Line Usage”. The launcher accepts the following argument forms for its op‐ tional pyarg, which mirror the * part at the end of a file’s “#!” line: −2 Launch latest 2.X version installed -3 Launch latest 3.X version installed -X.Y Launch specified version (X is 2 or 3) -X.Y−32 Launch the specified 32-bit version If both are present, command-line arguments have precedence over values given in “#!” lines. As installed, “#!” lines may be applied in more contexts (e.g., icon clicks). Launcher Environment Variables The launcher also recognizes optional environment variable set‐ tings,whichmaybeusedtocustomizeversionselectionindefault or partial cases (e.g., missing or major-only “#!” or py command argument): PY_PYTHON Version to use in default cases (else 2) PY_PYTHON3 Version to use in 3 partials (e.g., 3.2) PY_PYTHON2 Version to use in 2 partials (e.g., 2.6) These settings are used only by launcher executables, not when python is invoked directly. Python Windows Launcher Usage | 11
  • 26. Built-in Types and Operators Operators and Precedence Table1listsPython’sexpressionoperators.Operatorsinthelower cells of this table have higher precedence (i.e., bind tighter) when used in mixed-operator expressions without parentheses. Atomic terms and dynamic typing In Table 1, the replaceable expression items X, Y, Z, i, j, and k may be: • Variable names, replaced with their most recently assigned value • Literal expressions, defined in “Specific Built-in Types” • Nested expressions, taken from any row in this table, pos‐ sibly in parentheses Python variables follow a dynamic typing model—they are not declared, and are created by being assigned; have object refer‐ ences as values, and may reference any type of object; and must be assigned before appearing in expressions, as they have no de‐ fault value. Case is always significant in variable names (see “Name Rules”). Objects referenced by variables are automatically created, and automatically reclaimed when no longer in use by Python’s garbage collector, which uses reference counters in CPython. Also in Table 1, replaceable attr must be the literal (unquoted) name of an attribute; args1 is a formal arguments list as defined in“ThedefStatement”;args2isaninputargumentslistasdefined in “The Expression Statement”; and a literal ... qualifies as an atomic expression in 3.X (only). 12 | Python Pocket Reference
  • 27. The syntax of comprehensions and data structure literals (tuple, list, dictionary, and set) given abstractly in the last three rows of Table 1 is defined in “Specific Built-in Types”. Table 1. Python 3.X expression operators and precedence Operator Description yield X Generatorfunctionresult(returnssend() value) lambda args1: X Anonymous function maker (returns X when called) X if Y else Z Ternary selection (X is evaluated only if Y is true) X or Y Logical OR: Y is evaluated only if X is false X and Y Logical AND: Y is evaluated only if X is true not X Logical negation X in Y, X not in Y Membership: iterables, sets X is Y, X is not Y Object identity tests X < Y, X <= Y, X > Y, X >= Y Magnitude comparisons, set subset and superset X == Y, X != Y Equality operators X | Y Bitwise OR, set union X ^ Y Bitwise exclusive OR, set symmetric difference X & Y Bitwise AND, set intersection X << Y, X >> Y Shift X left, right by Y bits X + Y, X − Y Addition/concatenation, subtraction/set difference X * Y, X % Y, X / Y, X // Y Multiplication/repetition, remainder/format, division, floor division -X, +X Unary negation, identity ˜X Bitwise NOT complement (inversion) X ** Y Power (exponentiation) X[i] Indexing (sequence, mapping, others) X[i:j:k] Slicing (all three bounds optional) X(args2) Call (function, method, class, other callable) Built-in Types and Operators | 13
  • 28. Operator Description X.attr Attribute reference (....) Tuple, expression, generator expression [....] List, list comprehension {....} Dictionary, set, dictionary and set comprehension Operator Usage Notes • InPython2.Xonly,valueinequalitycanbewrittenaseither X != Y or X <> Y. In Python 3.X, the latter of these options is removed because it is redundant. • In Python 2.X only, a backquotes expression `X` works the same as repr(X), and converts objects to display strings. In Python 3.X, use the more readable str() and repr() built- in functions instead. • In both Python 3.X and 2.X, the X // Y floor division ex‐ pression always truncates fractional remainders, and re‐ turns an integer result for integers. • The X / Y expression performs true division in 3.X (always retaining remainders in a floating-point result), and classic division in 2.X (truncating remainders for integers) unless 3.X’s true division is enabled in 2.X with from __future__ import division or Python option -Qnew. • The syntax [....] is used for both list literals and list com‐ prehension expressions. The latter of these performs an implied loop and collects expression results in a new list. • The syntax (....) is used for tuples and expressions, as well as generator expressions—a form of list comprehen‐ sion that produces results on demand, instead of building a result list. Parentheses may sometimes be omitted in all three constructs. 14 | Python Pocket Reference
  • 29. • The syntax {....} is used for dictionary literals. In Python 3.X and 2.7, it is also used for set literals, and both dictio‐ nary and set comprehensions; use set() and looping state‐ ments in 2.6 and earlier. • The yield and ternary if/else selection expressions are availableinPython2.5andlater.Theformerreturnssend() arguments in generators; the latter is a shorthand for a multiline if statement. yield requires parentheses if not alone on the right side of an assignment statement. • Comparison operators may be chained: X < Y < Z produces the same result as X < Y and Y < Z, but Y is evaluated only once in the chained form. • The slice expression X[i:j:k] is equivalent to indexing with a slice object: X[slice(i, j, k)]. • In Python 2.X, magnitude comparisons of mixed types are allowed—converting numbers to a common type, and or‐ dering other mixed types according to the type name. In Python 3.X, nonnumeric mixed-type magnitude compar‐ isons are not allowed and raise exceptions; this includes sorts by proxy. • Magnitude comparisons for dictionaries are also no longer supported in Python 3.X (although equality tests are); comparingsorted(adict.items()) isonepossiblereplace‐ ment in 3.X. • Call expressions allow for positional and keyword argu‐ ments, and arbitrarily large numbers of both; see “The Ex‐ pression Statement” and “The def Statement” for call syntax. • Python 3.X allows ellipsis (literally, ..., and known by built-in name Ellipsis) to be used as an atomic expression anywhereinsourcecode.Thismaybeusedasanalternative topass orNone insomecontexts(e.g.,stubbed-outfunction bodies, type-independent variable initialization). Built-in Types and Operators | 15
  • 30. • Although uncertain at this writing, Python 3.5 or later may generalize the *X and **X star syntax to appear in data structureliteralsandcomprehensions,whereitwillunpack collections into individual items, much as it currently does infunctioncalls.See“TheAssignmentStatement”formore details. Operations by Category In this section, trailing parentheses are omitted from __X__ method names for brevity. In general, all built-in types support the comparisons and Boolean operations listed in Table 2 (al‐ though Python 3.X does not support magnitude comparisons for dictionaries or mixed nonnumeric types). Boolean true means any nonzero number or any nonempty col‐ lectionobject(list,dictionary,etc.),andallobjectshaveaBoolean value. The built-in names True and False are preassigned to true and false values and behave like integers 1 and 0 with custom display formats. The special object None is false and appears in various Python contexts. Comparisons return True or False and are automatically applied recursively in compound objects as needed to determine a result. Boolean and and or operators stop (short-circuit) as soon as a result is known and return one of the two operand objects—the value on the left or the right of the operator—whose Boolean value gives the result. Table 2. Comparisons and Boolean operations Operator Description X < Y Strictly less thana X <= Y Less than or equal to X > Y Strictly greater than X >= Y Greater than or equal to X == Y Equal to (same value) 16 | Python Pocket Reference
  • 31. Operator Description X != Y Not equal to (same as X<>Y in Python 2.X only)b X is Y Same object X is not Y Negated object identity X < Y < Z Chained comparisons not X If X is false then True; else, False X or Y If X is false then Y; else, X X and Y If X is false then X; else, Y aToimplementcomparisonexpressions,seeboththerichcomparison(e.g.,__lt__ for<)classmethodsin3.Xand2.X,andgeneral__cmp__methodin2.X,described in “Operator Overloading Methods”. b != and <> both mean not equal by value in 2.X, but != is the preferred syntax in 2.X and the only supported option in 3.X. is performs an identity test; == performs value comparison, and so is much more generally useful. Tables 3 through 6 define operations common to types in the three major type categories—sequence (positionally ordered), mapping (access-by-key), and number (all numeric types)—as well as operations available for mutable (changeable) types in Python. Most types also export additional type-specific opera‐ tions (e.g., methods), as described in “Specific Built-in Types”. Table 3. Sequence operations (strings, lists, tuples, bytes, bytearray) Operation Description Class method X in S X not in S Membership tests __contains__, __iter__, __getitem__a S1 + S2 Concatenation __add__ S * N, N * S Repetition __mul__ S[i] Index by offset __getitem__ Built-in Types and Operators | 17
  • 32. Operation Description Class method S[i:j], S[i:j:k] Slicing: items in S from offset i through j−1 by optional stride k __getitem__b len(S) Length __len__ min(S), max(S) Minimum, maximum item __iter__, __getitem__ iter(S) Iteration protocol __iter__ for X in S:, [expr for X in S], map(func, S), etc. Iteration (all contexts) __iter__, __getitem__ a See also “The iteration protocol” for more on these methods and their interplay. If defined, __contains__ is preferred over __iter__, and __iter__ is preferred over __getitem__. b In Python 2.X, you may also define __getslice__, __setslice__, and __delslice__ to handle slicing operations. In 3.X, these are removed in favor ofpassingsliceobjectstotheiritem-basedindexingcounterparts.Sliceobjectsmay be used explicitly in indexing expressions in place of i:j:k bounds. Table 4. Mutable sequence operations (lists, bytearray) Operation Description Class method S[i] = X Index assignment: change item at existing offset i to reference X __setitem__ S[i:j] = I, S[i:j:k] = I Slice assignment: S from i through j−1 with optional stride k (possibly empty) is replaced by all items in iterable I __setitem__ del S[i] Index deletion __delitem__ del S[i:j], del S[i:j:k] Slice deletion __delitem__ 18 | Python Pocket Reference
  • 33. Table 5. Mapping operations (dictionaries) Operation Description Class method D[k] Index by key __getitem__ D[k] = X Key assignment: change or create entry for key k to reference X __setitem__ del D[k] Delete item by key __delitem__ len(D) Length (number of keys) __len__ k in D Key membership testa Same as in Table 3 k not in D Converse of k in D Same as in Table 3 iter(D) Iterator object for D’s keys Same as in Table 3 for k in D:, etc. Iterate through keys in D (all iteration contexts) Same as in Table 3 a In Python 2.X, key membership may also be coded as D.has_key(k). This method is removed in Python 3.X in favor of the in expression, which is also generally preferred in 2.X. See “Dictionaries”. Table 6. Numeric operations (all number types) Operation Description Class method X + Y, X − Y Add, subtract __add__, __sub__ X * Y, X / Y, X // Y, X % Y Multiply, divide, floor divide, remainder __mul__, __truediv__a, __floordiv__, __mod__ −X, +X Negative, identity __neg__, __pos__ X | Y, X & Y, X ^ Y Bitwise OR, AND, exclusive OR (integers) __or__, __and__, __xor__ X << N, X >> N Bitwiseleft-shift,right- shift (integers) __lshift__, __rshift__ ˜X Bitwise invert (integers) __invert__ X ** Y X to the power Y __pow__ abs(X) Absolute value __abs__ Built-in Types and Operators | 19
  • 34. Operation Description Class method int(X) Convert to integerb __int__ float(X) Convert to float __float__ complex(X), complex(re,im) Make a complex value __complex__ divmod(X, Y) Tuple: (X / Y, X % Y) __divmod__ pow(X, Y [,Z]) Raise to a power __pow__ a The / operator invokes __truediv__ in Python 3.X, but __div__ in Python 2.X unless true division is enabled. See “Operator Usage Notes” for division semantics. b In Python 2.X, the long() built-in function invokes the __long__ class method. In Python 3.X, the int type subsumes long, which is removed. Sequence Operation Notes Examples and notes on selected sequence operations in Table 3 and Table 4: Indexing: S[i] • Fetches components at offsets (first item is at offset 0). • Negative indexes count backward from the end (last item is at offset −1). • S[0] fetches the first item; S[1] fetches the second item. • S[−2] fetches the second-to-last item (same as S[len(S) − 2]). Slicing: S[i:j] • Extracts contiguous sections of a sequence, from i through j−1. • Slice boundaries i and j default to 0 and sequence length len(S). • S[1:3] fetches from offsets 1 up to, but not including, 3. • S[1:] fetches from offsets 1 through the end (len(S)-1). 20 | Python Pocket Reference
  • 35. • S[:−1] fetches from offsets 0 up to, but not including, the last item. • S[:] makes a top-level (shallow) copy of sequence object S. Extended slicing: S[i:j:k] • The third item k is a stride (default 1), added to the offset of each item extracted. • S[::2] is every other item in entire sequence S. • S[::−1] is sequence S reversed. • S[4:1:−1] fetches from offsets 4 up to, but not including, 1, reversed. Slice assignment: S[i:j:k] = I • Slice assignment is similar to deleting and then inserting where deleted. • Iterables assigned to basic slices S[i:j] need not match in size. • Iterables assigned to extended slices S[i:j:k] must match in size. Other • Concatenation, repetition, and slicing return new objects (though not always for tuples). Specific Built-in Types This section covers numbers, strings, lists, dictionaries, tuples, files,sets,andothercorebuilt-intypes.Itssubsectionsgivedetails common to both Python 3.X and 2.X. In general, all the compound datatypes covered here (e.g., lists, dictionaries, and tuples) can nest inside each other arbitrarily and as deeply as Specific Built-in Types | 21
  • 36. 1. InPython2.X,thereisadistincttypenamedlongforunlimited-precision integers; int is for normal integers with precision that is usually limited to 32 bits. Long objects may be coded with a trailing “L” (e.g., 99999L), although integers are automatically promoted to longs if they require the extra precision. In 3.X, the int type provides unlimited precision and so subsumes both the 2.X int and long types; the “L” literal syntax is re‐ moved in 3.X. 2. In Python 2.X, octal literals may also be written with just a leading zero —0777and0o777areequivalent.In3.X,onlythelatterformissupported for octal. required. Sets may participate in nesting as well, but may contain only immutable objects. Numbers Numbers are immutable (unchangeable) values, supporting nu‐ meric operations. This section covers basic number types (inte‐ gers, floating-point), as well as more advanced types (complex, decimals, and fractions). Literals and creation Numbers are written in a variety of numeric literal forms, and created by some built-in operations: 1234, −24, +42, 0 Integers (unlimited precision).1 1.23, 3.14e-10, 4E210, 4.0e+210, 1., .1 Floating-point (normally implemented as C doubles in CPython). 0o177, 0x9ff, 0b1111 Octal, hex, and binary literals for integers.2 3+4j, 3.0+4.0j, 3J Complex numbers. 22 | Python Pocket Reference
  • 37. decimal.Decimal('1.33'), fractions.Fraction(4, 3) Module-based types: decimal, fraction. int(9.1), int('-9'), int('1111', 2), int('0b1111', 0), float(9), float('1e2'), float('-.1'), complex(3, 4.0) Create numbers from other objects, or from strings with possible base conversion. Conversely, hex(N), oct(N), and bin(N) createdigitstringsforintegers,andstringformatting makes general strings for numbers. See also “String format‐ ting”, “Type Conversions”, and “Built-in Functions”. Operations Number types support all number operations (see Table 6 on page 19). In mixed-type expressions, Python converts operands up to thetypeofthe“highest”type,whereintegerislowerthanfloating- point, which is lower than complex. As of Python 3.0 and 2.6, integer and floating-point objects also have a handful of type- specific methods and other attributes; see Python’s Library Ref‐ erence manual for details: >>> (2.5).as_integer_ratio() # float attrs (5, 2) >>> (2.5).is_integer() False >>> (2).numerator, (2).denominator # int attrs (2, 1) >>> (255).bit_length(), bin(255) # 3.1+ method (8, '0b11111111') Decimal and fraction Python provides two additional numeric types in standard li‐ brary modules—decimal is a fixed-precision, floating-point number, and fraction is a rational type that keeps numerator and denominatorexplicitly.Bothmaybeusedtoaddressinaccuracies of floating-point arithmetic: >>> 0.1 - 0.3 -0.19999999999999998 Specific Built-in Types | 23
  • 38. >>> from decimal import Decimal >>> Decimal('0.1') - Decimal('0.3') Decimal('-0.2') >>> from fractions import Fraction >>> Fraction(1, 10) - Fraction(3, 10) Fraction(-1, 5) >>> Fraction(1, 3) + Fraction(7, 6) Fraction(3, 2) Fractions automatically simplify results. By fixing precision and supporting various truncation and rounding protocols, decimals are useful for monetary applications. See the Python Library Ref‐ erence for details. Other numeric types Python also includes a set type (described in “Sets”). Additional numeric types such as optimized vectors and matrixes are avail‐ able as third-party open source extensions (e.g., see the NumPy package at http://www.numpy.org). The third-party domain also includes support for visualization, statistical tools, extended pre‐ cision floating-point math, and more (see the Web). Strings The normal str string object is an immutable (unchangeable) sequence of characters accessed by offset (position). Its charac‐ ters are code point ordinals in the underlying character set, and individual characters are string objects of length 1. The full string object model varies across lines. Python 3.X has three string types with similar interfaces: str An immutable sequence of characters, used for all text— both ASCII and richer Unicode. 24 | Python Pocket Reference
  • 39. bytes An immutable sequence of short integers, used for the byte values of binary data. bytearray A mutable variant of bytes. Python 2.X instead has two string types with similar interfaces: str An immutable sequence of characters, used for both byte oriented (8-bit) text and binary data. unicode An immutable sequence of characters, used for possibly- richer Unicode text. Python 2.X (as of 2.6) also has the Python 3.X bytearray type as aback-portfrom3.X,butitdoesnotimposeassharpadistinction between text and binary data. (It may be mixed with text strings freely in 2.X.) For Unicode support in both 3.X and 2.X, see “Unicode Strings”. Most of the remainder of this section pertains to all string types, but see “String methods”, “Unicode Strings”, and “Built-in Functions” for more on bytes and bytearray. Literals and creation String literals are written as a series of characters in quotes, op‐ tionally preceded with a designator character, and in all string literal forms an empty string is coded as adjacent quotes. Various built-in operations also return new strings: 'Python"s', "Python's" Single and double quotes work the same, and each can em‐ bed unescaped quotes of the other kind. """This is a multiline block""" Triple-quoted blocks collect multiple lines of text into a sin‐ gle string, with end-of-line markers (n) inserted between the original quoted lines. Specific Built-in Types | 25
  • 40. 'Python'sn' Backslash escape code sequences (see Table 7) are replaced with the special-character code point values they represent (e.g., 'n' is an ASCII character with decimal code-point value 10). "This" "is" "concatenated" Adjacent string constants are concatenated. Hint: this form may span lines if parenthesized. r'a rawstring', R'anotherone' Raw strings: backslashes are retained literally (except at the endofastring).UsefulforregularexpressionsandWindows (DOS) directory paths: e.g., r'c:dir1file'. hex(), oct(), bin() Create hex/octal/binary digit strings from integer numbers. See “Numbers” and “Built-in Functions”. The following literal forms and calls make specialized strings de‐ scribed in “Unicode Strings”: b'...' bytes string literal in Python 3.X: sequence of 8-bit byte values representing raw binary data. For 3.X compatibility, this form is also available in Python 2.6 and 2.7, where it simply creates a normal str string. See “String methods”, “Unicode Strings”, and “Built-in Functions”. bytearray(...) bytearray string construction: a mutable variant of bytes. Available in Python 3.X, and in Python 2.X as of 2.6. See “String methods”, “Unicode Strings”, and “Built-in Func‐ tions”. u'...' Unicode string literal in Python 2.X: a sequence of Unicode code points. For 2.X compatibility, this form is also available in Python 3.X as of 3.3, where it simply creates a normal str string (but normal string literals and str strings support Unicode text in Python 3.X). See “Unicode Strings”. 26 | Python Pocket Reference
  • 41. str(), bytes(), bytearray() (and unicode() in 2.X only) Create strings from objects, with possible Unicode encod‐ ing/decoding in Python 3.X. See “Built-in Functions”. String literals may contain escape sequences taken from Table 7 to represent special characters. Table 7. String constant escape codes Escape Meaning Escape Meaning newline Ignored continuation t Horizontal tab Backslash () v Vertical tab ' Single quote (‘) N{id} Unicode dbase id " Double quote (“) uhhhh Unicode 16-bit hex a Bell Uhhhhhhhh Unicode 32-bit hexa b Backspace xhh Hex (at most 2 digits) f Formfeed ooo Octal (up to 3 digits) n Line feed 0 Null (not end of string) r Carriage return other Not an escape a Uhhhhhhhh takes exactly eight hexadecimal digits (h); both u and U can be used only in Unicode string literals. Operations All string types support all sequence operations (see Table 3), plus string-specific methods (described in “String methods”). In ad‐ dition, the str type supports string formatting % expressions and template substitution (discussed next), and the bytearray type supportsmutable sequence operations(Table4,plusextralist-like methods). Also see the re string pattern-matching module in “The re Pattern-Matching Module”, and string-related, built-in functions in “Built-in Functions”. Specific Built-in Types | 27
  • 42. String formatting In both Python 3.X and 2.X (as of 3.0 and 2.6), normal str strings support two different flavors of string formatting—operations that format objects according to format description strings: • The original expression (all Python versions), coded with the % operator: fmt % (values) • The newer method (3.0, 2.6, and later), coded with call syntax: fmt.format(values) Both produce new strings based on possibly type-specific sub‐ stitution codes. Their results may be displayed, or assigned to variables for later use: >>> '%s, %s, %.2f' % (42, 'spam', 1 / 3.0) '42, spam, 0.33' >>> '{0}, {1}, {2:.2f}'.format(42, 'spam', 1 / 3.0) '42, spam, 0.33' Although the method call seems to have evolved more rapidly in recent years, the expression is used extensively in existing code, and both forms are still fully supported. Moreover, although some view the method form as marginally more mnemonic and consistent, the expression is often simpler and more concise. As these two forms are largely just minor variations on a theme of equivalent functionality and complexity, there is today no com‐ pelling reason to recommend one over the other. String formatting expression String formatting expressions replace % targets in the string on the left of the % operator, with values on the right (similar to C’s sprintf). If more than one value is to be replaced, they must be coded as a tuple to the right of the % operator. If just one item is to be replaced, it can be coded as a single value or one-item tuple on the right (nest tuples to format a tuple itself). If key names are used on the left, a dictionary must be supplied on the right, and * allows width and precision to be passed in dynamically: 28 | Python Pocket Reference
  • 43. >>> 'The knights who say %s!' % 'Ni' 'The knights who say Ni!' >>> '%d %s, %d you' % (1, 'spam', 4.0) '1 spam, 4 you' >>> '%(n)d named %(x)s' % {'n': 1, 'x': "spam"} '1 named spam' >>> '%(n).0E => [%(x)-6s]' % dict(n=100, x='spam') '1E+02 => [spam ]' >>> '%f, %.2f, %+.*f' % (1/3.0, 1/3.0, 4, 1/3.0) '0.333333, 0.33, +0.3333' Formatting expression syntax In the format string on the left of the % operator, substitution targets have the following general format, all but the last com‐ ponentofwhichisoptional(textoutsidesuchsubstitutiontargets is retained verbatim): %[(keyname)][flags][width][.prec]typecode In this substitution target syntax: keyname References an item in the expected dictionary, in parentheses. flags Can be − (left-justify), + (numeric sign), a space (use a blank before positive numbers and a − for negatives ), and 0 (zero fill). width The total minimum field width (use * to fetch from values). prec Gives the number of digits (i.e., precision) to include af‐ ter . (use * to fetch from values). typecode A character from Table 8. Specific Built-in Types | 29
  • 44. Both width and prec can be coded as a * to force their values to be taken from the next item in the values to the right of the % operator when sizes are not known until runtime. Hint: %s ge‐ nerically converts any object type to its print representation string. Table 8. % string formatting type codes Code Meaning Code Meaning s String (or any object, uses str()) X x with uppercase r s, but uses repr(), not str() e Floating-point exponent c Character (int or str) E e with uppercase d Decimal (base 10 integer) f Floating-point decimal i Integer F f with uppercase u Same as d (obsolete) g Floating-point e or f o Octal (base 8 integer) G Floating-point E or F x Hex (base 16 integer) % Literal ‘%’ (coded as %%) String formatting method The formatting method call works similar to the prior section’s expression, but is invoked with normal method-call syntax on theformatstringobject,whichidentifiessubstitutiontargetswith {} syntax instead of %. Substitution targets in the format string may name method-call arguments by position or keyword name; may further reference argument attributes, keys, and offsets; may accept default for‐ mattingorprovideexplicittypecodes;andmaynesttargetsyntax to pull values from the arguments list: >>> 'The knights who say {0}!'.format('Ni') 'The knights who say Ni!' >>> '{0} {1}, {2:.0f} you'.format(1, 'spam', 4.0) '1 spam, 4 you' >>> '{n} named {x:s}'.format(n=1, x="spam") '1 named spam' >>> '{n:.0E} => [{x:<6s}]'.format( **dict(n=100, x='spam')) 30 | Python Pocket Reference
  • 45. '1E+02 => [spam ]' >>> '{:f}, {:.2f}, {:+.{}f}'.format( 1/3.0, 1/3.0, 1/3.0, 4) '0.333333, 0.33, +0.3333' Most format method applications have equivalents in % expres‐ sion usage patterns as shown in the preceding section (e.g., dic‐ tionary key and * value references), although the method allows some operations to be coded inside the format string itself: >>> import sys # Method vs expr: attr, key, index >>> fmt = '{0.platform} {1[x]} {2[0]}' >>> fmt.format(sys, dict(x='ham'), 'AB') 'win32 ham A' >>> fmt = '%s %s %s' >>> fmt % (sys.platform, dict(x='ham')['x'], 'AB'[0]) 'win32 ham A' As of Python 3.1 and 2.7, a , (comma) preceding an integer or floating-point designation in typecode, formally described in “Formatting method syntax”, inserts thousands-separator com‐ mas, and a typecode of % formats a percentage (tools not present in the formatting expression itself, but straightforward to code as reusable functions): >>> '{0:,d}'.format(1000000) '1,000,000' >>> '{0:13,.2f}'.format(1000000) ' 1,000,000.00' >>> '{0:%} {1:,.2%}'.format(1.23, 1234) '123.000000% 123,400.00%' Also as of Python 3.1 and 2.7, field numbers are automatically numbered sequentially if omitted from the fieldname also de‐ scribed in “Formatting method syntax”—the following three have the same effect, although auto-numbered fields may be less readable if many fields are present: >>> '{0}/{1}/{2}'.format('usr', 'home', 'bob') 'usr/home/bob' >>> '{}/{}/{}'.format('usr', 'home', 'bob') # Auto Specific Built-in Types | 31
  • 46. 'usr/home/bob' >>> '%s/%s/%s' % ('usr', 'home', 'bob') # Expr 'usr/home/bob' A single object may also be formatted with the format(object, formatspec) built-in function (see “Built-in Functions”), which is employed by the string format method, and whose behavior may be implemented with the __format__ operator-overloading method in classes (see “Operator Overloading Methods”). Formatting method syntax Substitution targets in strings used for format method calls take the following general form, all four parts of which are optional, and must appear without intervening spaces (used here for clari‐ ty): {fieldname component !conversionflag :formatspec} In this substitution target syntax: fieldname An optional number or keyword identifying an argument, which may be omitted to use relative argument numbering in 2.7, 3.1, and later. component A string of zero or more .name or [index] references used to fetch attributes and indexed values of the argument, which may be omitted to use the whole argument value. conversionflag Introduced by a ! if present, which is followed by r, s, or a to call repr(), str(), or ascii() built-in functions on the value, respectively. formatspec Introducedbya: ifpresent,andconsistsoftextthatspecifies how the value should be presented, including details such as field width, alignment, padding, decimal precision, and so on, and ending with an optional datatype code. 32 | Python Pocket Reference
  • 47. The nested formatspec component after the colon character has a syntax of its own, formally described as follows (brackets in this denote optional components and are not coded literally): [[fill]align][sign][#][0][width][,][.prec][typecode] In this formatspec nested syntax: fill Can be any fill character other than { or }. align May be <, >, =, or ^, for left alignment, right alignment, padding after a sign character, or centered alignment, respectively. sign May be +, −, or space. , (comma) Requests a comma for a thousands separator as of Python 3.1 and 2.7. width and prec Much as in the % expression, and the formatspec may also contain nested {} format strings having a fieldname only, to take values from the arguments list dynamically (much like the * in formatting expressions). A 0 preceding width ena‐ bles sign-aware zero padding (similar to fill), and a # en‐ ables an alternative conversion (if available). typecode Largely the same as in % expressions and listed in Table 8, but the format method has an extra b type code used to give integers in binary format (much like using the bin built-in); has an extra % type code to format percentages as of Python 3.1 and 2.7; and uses only d for base-10 integers (i or u are not used). Note that unlike the expression’s generic %s, the method’s s type code requires a string object argument; omit the type code to accept any type generically in the method. Specific Built-in Types | 33
  • 48. Template string substitution As of Python 2.4, another form of string substitution is provided as an alternative to the string formatting expression and method described in the prior sections. In full formatting, substitution is achieved with the % operator or str.format() method (all four of the following return '2: PR5E'): '%(page)i: %(book)s' % {'page': 2, 'book': 'PR5E'} '%(page)i: %(book)s' % dict(page=2, book='PR5E') '{page}: {book}'.format(**dict(page=2, book='PR5E')) '{page}: {book}'.format(page=2, book='PR5E') For simpler substitution tasks, a Template class in string uses $ to indicate a substitution: >>> import string >>> t = string.Template('$page: $book') >>> t.substitute({'page': 2, 'book': 'PR5E'}) '2: PR5E' Substitution values can be provided as keyword arguments or dictionary keys: >>> s = string.Template('$who likes $what') >>> s.substitute(who='bob', what=3.14) 'bob likes 3.14' >>> s.substitute(dict(who='bob', what='pie')) 'bob likes pie' A safe_substitute method ignores missing keys rather than raising an exception: >>> t = string.Template('$page: $book') >>> t.safe_substitute({'page': 3}) '3: $book' String methods In addition to the format() method described earlier, string method calls provide higher-level text processing tools beyond string expressions. Table 9 lists available string method calls; in this table, S is any string object (technically, a 3.X str). String 34 | Python Pocket Reference
  • 49. methods that modify text always return a new string and never modify the object in-place (strings are immutable). For more details on methods in the table, see the functional area description sections ahead, or run a help(str.method) interac‐ tively. Hint: this list can vary across Python releases; to see yours, try: sorted(x for x in dir(str) if not x.startswith('__')) See also the re module in “The re Pattern-Matching Module” for pattern-based equivalents to some string type methods. Table 9. Python 3.X string method calls S.capitalize() S.casefold() (as of Python 3.3) S.center(width, [, fill]) S.count(sub [, start [, end]]) S.encode([encoding [, errors]]) S.endswith(suffix [, start [, end]]) S.expandtabs([tabsize]) S.find(sub [, start [, end]]) S.format(*args, **kwargs) S.format_map(mapping) (as of Python 3.2) S.index(sub [, start [, end]]) S.isalnum() S.isalpha() S.isdecimal() S.isdigit() S.isidentifier() S.islower() S.isnumeric() S.isprintable() Specific Built-in Types | 35
  • 50. Another Random Document on Scribd Without Any Related Topics
  • 54. The Project Gutenberg eBook of Virginia's Adventure Club
  • 55. This ebook is for the use of anyone anywhere in the United States and most other parts of the world at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this ebook or online at www.gutenberg.org. If you are not located in the United States, you will have to check the laws of the country where you are located before using this eBook. Title: Virginia's Adventure Club Author: Grace May North Illustrator: Elizabeth Colborne Thelma Gooch Release date: May 1, 2020 [eBook #61987] Most recently updated: October 17, 2024 Language: English Credits: Produced by Roger Frank and the Online Distributed Proofreading Team at https://www.pgdp.net (This file was produced from images generously made available by The Internet Archive) *** START OF THE PROJECT GUTENBERG EBOOK VIRGINIA'S ADVENTURE CLUB ***
  • 58. “I’m not scared of you,” she said.
  • 59. VIRGINIA’S ADVENTURE CLUB By GRACE MAY NORTH Author of “Virginia of V. M. Ranch,” “Virginia at Vine Haven,” “Virginia’s Ranch Neighbors,” “Virginia’s Romance.” A. L. BURT COMPANY Publishers New York Printed in U. S. A.
  • 60. THE VIRGINIA DAVIS SERIES A SERIES OF STORIES FOR GIRLS OF TWELVE TO SIXTEEN YEARS OF AGE By GRACE MAY NORTH VIRGINIA OF V. M. RANCH VIRGINIA AT VINE HAVEN VIRGINIA’S ADVENTURE CLUB VIRGINIA’S RANCH NEIGHBORS VIRGINIA’S ROMANCE Copyright, 1924 By A. L. BURT COMPANY VIRGINIA’S ADVENTURE CLUB Made in “U. S. A.” VIRGINIA’S ADVENTURE CLUB
  • 61. CHAPTER I THE ADVENTURE CLUB “Now that the Christmas holidays are over,” Babs remarked on the first Monday evening after the close of the short vacation, “I mean to redeem myself.” Margaret Selover looked down at the Dresden China girl who, her fluffy golden curls loosened from their fastenings, was wearing a blue corduroy kimona which matched her eyes. Babs sat tailorwise upon the furry white rug close to their grate fire. Megsy laughed. “Which means?” she inquired as she sat in front of her birds-eye maple dressing table, brushing her pretty brown hair. “Which means that I have determined to startle the natives by getting my name on the honor roll. Watchez-vous me! See if I don’t.” “I certainly admire your French.” Margaret was donning her golden brown robe that was woolly and warm. Then, when she, too, was seated opposite her roommate, she inquired: “But why this sudden ambition? I thought your motto has always been ‘Learn as little as you can, for wisdom makes a stupid man.’” “Well, doesn’t it?” Babs flashed. “Take Professor Crowell fer instance. He probably knows as much as the encyclopædia, and yet, who can deny but that he is stupid. He goes around ruminating on things that nobody else could understand, and he can’t even tell his own daughters apart.” Margaret laughed. “Well, belovedest, I don’t think you and I are either of us in danger of becoming as wise as Professor Crowell, and as for telling Dora and Cora apart—who can? Certainly not Mrs. Martin, and they’ve been in this school since they were small.” Then more seriously, she clasped her hands over her drawn-up knees, Margaret continued: “But I would like to be as wise as Miss
  • 62. Torrence. When she is reading to us and there is a reference to someone or something that happened in the long ago, you know how her eyes brighten. She is seeing a picture that represents it. I know, because yesterday when I came across a reference to the Peripatetic school, I was as pleased as Punch. I knew at once that the Greek word meant ‘to walk,’ and that it had been used because Aristotle, the greatest of ancient philosophers, walked up and down in his garden while teaching. And so I have decided that, if learning does nothing else, it adds a lot to one’s own pleasure.” Babs glanced at the clock over the mantle. “I don’t see why the girls don’t come,” she said, trying to suppress a little yawn. Margaret laughed and leaned over to poke up the fire. “My professorial discourse has evidently made you sleepy. Hark! I believe I hear approaching giggles.” A merry tattoo on the closed door announced the arrival of the expected guests, and in they trooped, each wearing a bath robe or warm kimona of the color which the owner believed to be most becoming to her particular type of beauty. Betsy Clossen, in a brilliant cherry-red robe, was the first to burst in. Then, observing the solemn faces of the two before the fire, she remarked inelegantly: “For Pete’s sake, who died? I thought we were going to have a giggle-fest to celebrate our reunion, after the long separation, and here are our hostesses looking as though they had just heard that they’d both failed in the final tests.” The newcomers dropped down on chairs or floor, as they preferred. Barbara continued to look unusually solemn. “That’s just it,” she announced. Then to Margaret: “That’s why I told you awhile ago that I mean to redeem myself. I flunked on the holiday tests, and I was the only one in our crowd who did. Even Betsy—” She paused and there was a mischievous twinkle in the blue eyes that had been serious longer than was their wont. “Believe me, I just got through by the skin of my teeth!” that maiden announced in her characteristic manner. “Spent too much time playing detective, and failed at that, too.”
  • 63. “I’ll tell you what!” Virginia Davis, who had been a sympathetic listener, spoke for the first time. “Let’s have a study club and meet in one of our rooms every Saturday evening and have an oral review of the week’s work.” “Ooh!” moaned Betsy; “that doesn’t sound very interesting.” “I’m for it,” Babs announced; “and when the grind part is over, couldn’t we have refreshments?” This, hopefully. “Why, of course. We are always allowed to make fudge on Saturday evening—” Virginia had begun, when Betsy put in: “Oh, I say; please change the name of it; then I’ll enjoy it heaps more, if one can enjoy anything related to learning.” “Can’t we think up some name that won’t sound the least bit studious? Then we can have the real object a secret.” “We might call it The Adventure Club if you would enjoy the meetings more than you would if we called it The Weekly Review.” Margaret smilingly suggested. “I’m for it,” Betsy declared, then added doubtfully. “I suppose my new roommate will think she ought to be let in on it. Would any of you mind? She’s not such a bad sort.” “Who did you draw, Bets? I thought you hoped you were to have your room alone this term.”’ “So did I, but Fate was agin’ me. Just as I was spreading my duds all over the room, thinking I was to be sole possessor, along came Mrs. Martin with a roommate for me. Since Sally MacLean didn’t come the first term, I didn’t ever expect her back again.” “Sentimental Sally!” Babs and Megsy exclaimed in one breath. “Has she returned to Vine Haven?” A doleful nod was Betsy’s only reply. Then she laughed gaily as though at some merry memory. “I suppose you girls who don’t know her are wondering why we call her ‘Sentimental Sally,’ and so I’ll tell you.” “Well, proceed. We’re all ears, as the elephant’s child was once heard to remark,” Barbara said as she leaned back against Virginia, who sat in the easy willow chair. “Is this Sentimental Sally, silly?” Virg inquired.
  • 64. Betsy laughed. “Silly?” she repeated with rising inflection, “She’s worse than that. She’s bugs! Or rather, she was. I sort of think she’s cured. Time alone will tell.” “Sally is always in love or thinks she is, which is perfectly ridiculous,” Margaret explained, “since she is only fifteen.” “I’ve sometimes thought that if Sally had had brothers, as we have, she wouldn’t have had such foolish notions,” Barbara remarked. “You have the floor now, Betsy, tell the girls the woeful tale of Sally’s downfall.” “Well, to begin at the beginning, Miss Snoopins, otherwise known as the Belligerent Buell, is death on members of the sex not fair.” “Meaning boys,” Barbara put in. “One of the rules that she made for the corridors was that no photographs of the objectionable creatures should be displayed in our rooms. Well, as usual, Sally was being sentimental about somebody, and the somebody was certainly a most good-looking boy. She called him ‘Donald Dear’ and raved about him whenever she could find anyone to listen. “Of course she wanted to have his photo in her room, but that was against the rules, so she got around it in this way. Her grandmother’s picture was in a frame that was suspended between two little gilt pillars and could be swung over with the back to the front, so to speak. Sally fastened her Donald’s picture back of her grandmother’s photo, and when she was all alone in the room, the boy smiled out at her, but when she heard footsteps in the corridor, she darted to the mantel and turned it over that her grandmother’s face might be the one to greet whoever was about to enter. In this way Sally evaded Miss Snoopins for a long time, but we knew that a day of reckoning would surely come. Nor were we mistaken. “We were all in her room on Thanksgiving. Maybe I ought to be ashamed to confess that, silly as we thought her, we were willing enough to partake of the spreads that came to her from a doting mother on any and all holidays. Sally is good-natured and she just adores me. Not much of a comp, considering her lack of brains, but anyway when we got a bid to her room for a Thanksgiving spread,
  • 65. we were all there, Megsy, Babs, Dicky Taylor and the present speaker. The craziest part of it was that we might have had that spread early in the evening, with permission, if we had wished, but that wouldn’t have been romantic enough to suit Sally. She wanted to wait until the lights-out bell had rung and then, when Miss Snoopins had passed down the hall, to be sure that the gong had been obeyed, she wanted us to all steal into her room, which we did. Sally then locked the door and hung a towel over the keyhole and drew the rug over the crack at the bottom. We forgot that light might also shine through the crack at the top. Then Sally lighted her prized candelabra and set it on the floor in the middle of a big paper table cloth. Oh, baby, it makes me hungry now to think of that spread. Say, Babs, do you remember how tender and juicy that turkey was? Yum! And those cranberries?” Megsy and Barbara nodded. Virginia smiled. “I’ve read boarding school stories,” she said, “and there was always some such prank. I suppose that just as the feast was about to be eaten, there came a knock on the door and—” But Betsy shook her head. “No, not that soon, thanks be. We had the turkey devoured even to the bones and were starting on the dessert, when Sally happened to look up at the mantle. If there wasn’t the kindly-faced old grandmother smiling down at us. For once Sally had forgotten to turn it over. Up she sprang and ‘Donald Dear’ beamed out. Then, to prove just how sentimental she really was, Sally lighted two tiny candles, one on either side of the frame. “He certainly was a handsome chap, and we all talked about him as we ate the delicious pumpkin pie. We asked Sally where she had met him, how old he was and if she were going to marry him when she grew up. She said yes indeed, that they were engaged and that he just adored her. The only reason that he didn’t write to her every day in the week was because pupils at Vine Haven weren’t allowed to have letters from boys. Of course we knew that. Now I happened to remember something which was, that the first time that Sally had told me about Donald, she had said that he was a class-mate of a boy cousin and that she had met him at her aunt’s summer home, but that night she told the girls that she had met Donald at a dance
  • 66. when she was visiting in Boston. Of course, being the daughter of the most famous detective that ever was, I noticed that discrepancy, though none of the other girls did, and I got suspicious at once. If Sally didn’t know where she had met the handsome Donald (we all agreed he was that), the question was had she really met him at all? “However, I didn’t want to spoil the spread by asking any embarrassing questions, but you know how tickled I was to have something to detect. Well, I was just eating my last luscious bite of mince pie when I pricked up an ear, so to speak. ‘Hist!’ I whispered, holding up one finger. ‘Didst hear a prowler?’ The girls all sprang up on the alert. “Of course we expected Miss Snoopins to appear and were prepared for the worst.” The narrator paused to be sure that she had properly aroused the curiosity of her listeners, and then she continued: “There was no mistaking the fact that there were footfalls without, then a voice said: ‘Open the door, young ladies, if you please.’ And it wasn’t the voice of Miss Snoopins. It was no less a personage than Mrs. Martin who stood there when the door was opened. Sally had at once darted to the mantel to reverse the picture in the swinging frame, but we made no attempt to hide the feast. It just couldn’t be done. My! but weren’t we skeered! We were sure we’d all get our walking papers, but though Mrs. Martin delivered a short lecture on setting an example to younger girls, she said kindly: ‘This was absolutely unnecessary, Sally, for you know I am always perfectly willing to permit you to share the box of good things that your mother sends you.’ “Miss Snoopins, who of course had brought Mrs. Martin, stood back of our beloved principal and she fairly glared at us. One could plainly see that she was boiling within and more than ever wrathful because Mrs. Martin was not severe. Suddenly her X-ray glance, which had been sweeping over the floor with its evidences of guilt, chanced to fall upon the mantel. Into the room she strode, looking like a caricature in her flannel nightie, her skimpy kimona and her flapping bedroom slippers. Never before had her nose looked so long
  • 67. and peaked or her thin hair so tightly drawn back. When Sally saw the direction she was taking she looked, and to her horror she beheld that in her haste she had whirled the picture over twice, and that Donald dear was again smiling down upon the company. “Mrs. Martin, having asked us to promise that we would obtain permission to have a feast, in the future, had retired and so she did not hear or see what followed. Miss Snoopins’ green eyes fairly snapped. ‘Sally MacLean, is that a boy’s picture?’ she demanded. “There being no answer needed, Sally gave none, but she felt like crying, she said, when the belligerent Buell snatched it from the back of the frame to which it had been pinned and tore it into shreds. Even the pieces she thrust into the pocket of her kimona. ‘One hundred buttonholes in garments for the heathen,’ she said in no quiet voice. In fact, all the girls on our corridor were awakened, and the first to thrust their heads in at the door were Dora and Cora Crowell, and weren’t they mad when they saw that we had had a feast and that they weren’t in on it, but they were all back in their rooms before Miss Snoopins left which she did after ordering us out and watching us go. “Sally said she cried all night. She didn’t care to live without a picture of her dear Donald. I said her cousin could send her another picture of his roommate, but she didn’t reply. However, she looked so sort of queer that I was more than ever sure that she was just using her imagination. “Nothing happened until Valentine’s day, and you remember, Megsy, that Mrs. Martin said that Benjy Wilson might bring over a few of his friends from the Drexel Military Academy to call and that one of the teachers, Miss King, if she were free, would act as chaperone. “That was a great occasion for the girls. Mrs. Martin excused us from classes, as the calls were to be in the afternoon and Miss King took that opportunity to drill us in how to receive visitors. After half an hour of practice we skipped up to our rooms to get ready. We put on our prettiest white dresses with gay colored sashes. Margaret and Babs were to pour chocolate and Sally and I were to pass plates of
  • 68. wafers. This reception was for all of our sophomore and senior girls. Of course, Sentimental Sally was more excited than any of the rest of us, although we were all interested. It was a pleasant break in the monotony of school life. Eleanor Pettes had a single room at the front of the house last year, and just as we were all dressed and waiting for a signal to call us downstairs, Eleanor beckoned and we flocked to her room. ‘Here they come,’ she whispered, as though they could hear, ‘and don’t they look handsome, all of them in blue and gold dress uniforms.’ “They certainly did. There were about fifteen boys walking two by two with Sergeant Hinkle, one of the seniors, in charge. Sally had been at her mirror arranging her yellow curls in just the right places, and so she hadn’t looked out the window, but she was ready a second later when Miss King appeared to lead us downstairs. “The boys were standing about in the library looking at the books on the shelves or pretending to when we entered. Miss King spoke first with Sergeant Hinkle, and then we were all introduced in a rather general way, and we stood about talking in groups. I said to Sally: ‘There are two boys over by the window and they look lonely. Let’s go and talk with them.’ “‘All right,’ Sally agreed, ‘you lead the way.’ “Sally followed as I wedged through the groups, but when we got there we found only one boy who stood with his arms folded looking about the room with rather an amused expression on his really good-looking face. He turned toward us questioningly for Sally had uttered a little cry of amazement and had put her hand to her heart. “Of course, I had recognized the boy at once. He was Donald Dear! He looked at us pleasantly, even curiously, as he noted Sally’s very evident agitation, but it was perfectly plain to me that he had never seen either of us before. “‘What did Sally say?’ Virginia inquired. “‘She didn’t say—she bolted! She went up to her room and when the callers were gone I found her there in tears.’ “‘She said that we’d all think she was a fibber, and that’s what she really had been, for she hadn’t the least idea who the boy was in the
  • 69. photograph. She just knew that he was a football player whose picture was among a lot that her cousin had brought home from school. She said she was just crazy about him and always would be.’ “‘Did Sally ever see him again?’ Virg inquired. “‘No, I guess not. Benjy said that Donald Dearing went to France soon after that to be with his father, who was stationed there.’ “Margaret looked meditatively into the fire. ‘If only girls knew how much more boys like them when they are not sentimental,’ she said, ‘they would all try to be just good comrades.’ “‘Sally didn’t return to Vine Haven the next term,’ Betsy continued. ‘Honestly, I felt sorry for her, and so I wrote her a Christmas letter and told her the girls didn’t hold it against her because she had used her imagination. She was so happy to get that letter and she packed right up and came back to school.’ “‘Poor girl!’ Virginia said kindly. ‘Do bring her to the meetings of The Adventure Club. Perhaps it will do her a lot of good. Don’t you think so, everybody?’ “Babs and Margaret nodded. ‘I always liked Sally, and I’m pretty sure that she won’t be sentimental again,’ Megsy replied.” A get-ready-for-bed gong was pealing through the corridors and the girls arose. “This is Monday,” Babs announced. “I’m going to study like a good one, so I’ll know every question asked me at the Saturday Evening Review.”
  • 70. CHAPTER II SENTIMENTAL SALLY Sally MacLean entered Barbara’s room almost shyly on the following Saturday evening. She was pleased because Betsy had invited her to attend The Adventure Club’s first gathering, but remembering her humiliation of the year before, she was not sure how she would be received. But the old pupils acted just as though nothing had ever happened and Virginia welcomed Sally, whom she had not chanced to meet since her arrival, in her friendliest manner. “Shall we begin the review at once?” the older girl asked. “Oh, dear me, no!” Betsy protested. “If this is going to be a club, let’s elect officers and frame rules, if that’s what it’s called, and choose a motto an’ everything.” “I choose to be committee on refreshments,” Babs sang out. “I choose to be club detective,” Betsy put in. “I vote for Virginia for president,” Margaret said. “Second it! Third it! Fourth it!” came a succession of merry voices. “Winona you may be secretary and I’ll be treasurer if there is to be anything to treasure.” Margaret happened to glance at the slight girl who sat somewhat in the shadow. “Draw your chair into the firelight, Sallykins,” she called pleasantly. “How can you expect to be elected to an office if you’re out of sight.” The youngest member drew her chair forward, and when the flood of light from the student lamp fell upon her doll pretty face and her long yellow curls that hung to her waist, Virginia, for the first time, had a real opportunity to observe her. “Poor girl!” she thought. “She has been too much petted and pampered by a rich mother, I guess, to develop any real character. How pretty she would be, with those dark blue eyes and long curling
  • 71. lashes, if her face wasn’t so weak. Perhaps the club will be able to help her.” Virginia’s meditations were interrupted by Margaret, who was asking, “Every one of us is holding an office except Sally. What can she be?” “I choose her for my assistant,” Virg said. “Whizzle! What an honor! Sal, think of that for dizzy soaring. Up from the common ranks all in a jiff to vice president.” Sally flushed, looking prettier than before. “I never do know, Betsy,” she said feebly, “whether you’re making fun or not.” Margaret intervened. “Just decide that she always is,” she suggested. “I never knew Betsy Clossen to be solemn.” “Then Mistress Megsy, you’re going to have a brand new experience, for I am going to be solemn five minutes by the clock.” Turning to Virginia she asked, her expression as big-eyed and serious as she could make it, “Madame President, we have two objects for this club, one to study and one to eat. We have each been appointed to an office of honor. It merely remains now for us to select a fitting motto.” Virginia smiled and the other girls laughed, but Betsy looked reproachfully from one to the other and they could not make her change her solemn expression. “Everybody think a moment,” Virg suggested, but almost at once Babs sprang up and clapped her hands. “I know where there are steens and steens of mottos, any one of them would do.” “Where?” Megsy inquired. “On my motto calendar. I’ll tell you what, Virg. You select a date and I’ll read the motto that’s under it.” “Well, then, January fifteenth, which is today.” Barbara skipped to her bird’s-eye maple writing desk and read from the small pad calendar. “Do the work that’s nearest, Though it’s dull at whiles.
  • 72. Helping when you meet them, Lame dogs over stiles.” Virginia smiled. “That’s excellent,” she said, “and let’s begin to put it into effect. To do the work that’s nearest, Babs, please hand me that pile of books yonder and I’ll begin the weekly review.” “Ooh!” Betsy sank far down in her chair and looked so despondent that the others laughed. “Let’s get this part over as quickly as ever we can,” Barbara begged. “I’m almost famished for fudge.” The review that evening proved two things to the president of the club. One was that Barbara had really studied during the week that had just ended and her pretty flushed face and eager way of answering showed that at last she was really interested in learning. But when Sally was asked to repeat William Cullen Bryant’s “Thanatopsis,” the poem that all of the girls in Miss Torrence classes were required to memorize soon or late, that doll-like little maid became so confused that Virginia quickly realized that she had no understanding of what the lines meant. “Girls,” Virginia said, looking at the others rather than at the embarrassed newcomer, “there is only one real way to learn poetry, I think, and that is to first picture what it means. When we thoroughly understand the sentiment, we can far more easily memorize the words of the poem.” Then very kindly, “Sally, what picture came to you when you recited the lines “To him who in the love of nature holds Communion with her visible forms, she speaks A various language; for his gayer hours She has a voice of gladness and a smile And eloquence of beauty, and she glides Into his darker musings with a mild And healing sympathy that steals away Their sharpness ere he is aware.” There was an almost startled expression in the baby-blue eyes that turned toward the speaker. “Why, I don’t believe I saw any
  • 73. picture. I was just trying to remember how the words came.” Margaret spoke. “Virginia,” she said, “those lines always mean one thing to me. When father died, I felt as though I could not stay in the house. The very walls oppressed me and so I ran away to a little woods that we owned and where father and I had often walked after mother left us. I had been sobbing for hours in my room and it was late afternoon when I reached the wood. I threw myself down on the moss near a little fern edged stream and though I cried at first, the gentle murmur of those great old trees seemed to soothe me and brought a peace and somehow I felt, that, though I could not see him, my dear father was still with me. Ever since then I have loved Thanatopsis and have better understood its meaning.” “Too, it is true that nature companions our happier moods with gladness and song,” Virginia said. “Many a time when I have felt joyous and have galloped on Comrade across the shining desert; the shout of the wind; the frolicking of the rabbits; the very mountain peaks seemed to be rejoicing with me. Nature truly is a wonderful companion.” Sally was listening with intelligent interest. “Oh, I believe I could recite it now, Virginia. I think I understand better what it means.” And she did, no longer afraid. That ended the review for the evening and Betsy leaped up to pass the fudge and this time she generously turned the plate so that Babs would be obliged to take the piece that was nuttiest, it being nearest her. That night when Virginia and Winona had returned to their room, they stood for a few moments, after the lights had been put out, to gaze toward the ocean, over which hung one burning star that was much larger than any of the others. Its path of quivering gold led toward the shore. They had opened the window and they could hear the murmurous plash of the waves on the sand, for the tide was out, and the surf was not crashing against the cliffs. These two, who so loved and understood nature, were quiet for a time. Then Winona spoke. “Virg,” she said, “I have felt a strange
  • 74. stirring within of late. It isn’t discontent, but a soul-voice is urging me to do something really worthwhile.” The light had been turned on again and the girls were preparing for bed. “What are you planning to do, Winona, that will be more worthwhile?” Virginia was sure that her Indian friend had not spoken without giving the matter long and earnest contemplation. “I do not feel that this school is just the place that I should be.” Then she hastily continued when she saw an expression of concern in the face of her dearly loved companion, “I’m not unhappy here, white Lily, but I seem to know that something else is waiting for me to do. I shall be ready when it comes.” They said no more that night as the last “lights-out” bell was ringing and after that, silence in the rooms was the rule. Virginia lay awake a long time watching the star that hung like a lantern in the bit of dark blue of the sky that was framed in her window. Her thoughts were of Winona. How calm and strong she was. She would indeed be ready when the call came to do the worthwhile thing, whatever sacrifice might be required of her.
  • 75. CHAPTER III A SECRET ENEMY “Hist. Virg, hold on a minute!” The tall slender girl warmly wrapped in hood and long cloak turned in surprise as she was about to enter the little pine wood, beyond which lay the cabin of her beloved teacher and friend Miss Torrence. She was indeed puzzled when she saw Betsy equally well protected from the sleet and snow arise from a clump of bushes near the path. “How you startled me,” the older girl said, “with that mysterious sounding ‘Hist’ of yours. Do detectives always do that?” “I don’t know,” Betsy confessed. “I never did hear my dad say it and he’s the only detective of my acquaintance.” Then stepping over a snow bank that she might stand in the shoveled path, she continued, “I wanted to waylay you. I’ve something to tell you. I really hate to. It sounds sort of sneaky, but we of The Adventure Club have just got to stand together and protect each other, haven’t we, Madame President?” “Why, yes. I think we should. What have you heard?” “Well, I didn’t have much of anything to do this morning, being as it’s Saturday and I thought I’d go up to the Tower Room that’s been vacant since Gwendolyn Laureat went away before Christmas. I never will know why I stole up those stairs as quietly as ever I could, unless it’s because sleuths in the movies always do steal about that way. When I got to the top of the stairs, I saw that the door was closed. There was nothing particularly strange about that, but, just as I had my hand on the knob to turn it, I heard voices inside. I tell you, it gave me a start! I remembered all the stories about that room being haunted and I was just about to dart away when I
  • 76. recognized one of the voices. The speaker stood so close to the door I could hear what she said. It was Kathryn Von Wellering and from what she was saying I knew that she is your enemy.” “My enemy?” Virginia exclaimed in surprise. “Why, what have I done to make Miss Von Wellering dislike me? All of the girls in that ‘Exclusive Three’ group have failed to know that I exist.” Betsy looked wise. “Don’t you remember that your story was voted first place in last term’s contest and that her story came out third? She had boasted about among her set that she would be the next Editress of The Manuscript Magazine and she isn’t used to not having what she wants.” “Oh, that’s it. But what can she do?” “What I heard her say was that she was going to see to it that the first copy of the magazine was such a failure that Miss Torrence would gladly appoint her as Editor.” Virginia looked troubled. “I’m truly sorry about this. I never did want the position and if Miss Von Wellering really wants it, I shall be glad to give it to her.” “Well, you’ll freeze, Virg, if I keep you standing out in this snowstorm any longer, but I just want to tell you that I heard one of the three say that you would find, at the last minute, that your own story was the only usable contribution that you would receive.” “Why, that can’t be possible. Miss Torrence told me this very morning that she would have a short story by Anne Peterson and a poem by Belle Wiley to give me before the Manuscript Magazine is made up.” “It certainly is too bad that Eleanor Pettes decided to go to college prep this term instead of coming here,” Virginia sighed. “She would know just what to do.” Then, brightly, “But I must hurry along. It was lucky that I started earlier than usual for Pine Cabin or I would be dolefully late.” “I’ll keep my eyes and ears open,” Betsy promised as she began to walk backwards toward the school. “But don’t give up the ship, Virg. Stick at your post and we’ll back you. Whizzle, I’ll write a story myself or a poem, even, if you run short of material.” Then, turning,
  • 77. she started to run, while Virginia continued on her way smiling, as she thought of what the Manuscript Magazine would be, if Betsy Clossen tried to write for it. Betsy’s forte most certainly was not composition. When Virg entered the Pine Cabin whither she had gone alone to discuss the first edition of The Monthly Magazine, which had been Miss Torrence’s pet hobby since she first began to teach at Vine Haven, the girl noted a perplexed expression in the eyes of her friend and teacher as she looked up from her desk that was scattered over with papers. “Virginia,” Miss Torrence began at once, “I cannot understand in the least what has happened. The story and poem that have been handed in by Anne Petersen and Belle Wiley are not fit to use. They never before did such poor work. In fact, these contributions do not sound at all like their style of composition. I was particularly anxious to have our January Manuscript Magazine an excellent one as Dean Craig of the Drexel Academy was asking me about the plan and requested that he might see our January number. He may start a similar magazine in his English classes. We surely can’t use work as poor as this and there remains but one week in which to find a really excellent short story. Kathryn Von Wellering has withdrawn her story saying that it cannot be used unless she is given the position of editor.” “I’d be glad to let her have it,” Virg said, but Miss Torrence shook her head. “Character as well as literary ability are taken into consideration when we appoint a girl at Vine Haven to a post of honor, and Kathryn’s influence is not of the best. Well, we have a week to try to unearth a worthwhile story.” Virginia soon left, wondering where a story was to be found. Virg thought often that snowy Saturday about what both Miss Torrence and Betsy Clossen had told her. It was hard to believe that she had a real enemy, she who had befriended everything that lived and who felt kindly toward all. “Virg, I believe that you actually would give up the post of honor that you have won,” Margaret declared that evening as she prepared
  • 78. for a second meeting of The Adventure Club. “Why not?” the girl addressed glanced up brightly. “It was an honor thrust upon me, not one that I coveted. It isn’t bringing me any great happiness and it has brought me an enemy. Who will, may have it, or, I mean, could-if it were within my power to dispose of it, but Miss Torrence has expressed her desire that I retain the position whether or not we receive contributions considered worthy of acceptance.” “Betsy declares that she is going to submit a poem.” This from Sally who was less timid than she had been at a previous meeting. Then she tittered in a way which made her seem even more foolish than she really was. “That’s why she’s late. She’s sitting curled up in our room writing it now.” “The Fates deliver us from any poetry that Betsy might write,” Margaret had just said when there came a pounding on the door, and, clad in her cherry-red bath robe, the object of their conversation burst into the room waving a sheet of foolscap paper. “It’s done! The day is saved. Never before will there have been an edition of The Manuscript Magazine to contain a literary gem like this.” The other members of the study club looked at each other in mock despair. “Must we endure the torture?” Babs moaned. “Get it over with as soon as you possibly can, if it must be done,” Margaret pleaded. Virginia interposed. “Girls, how dreadful of you! It might be good.” Betsy solemnly bowed, her hand on her heart. “Lady, I thank you for them kind words,” she said. Then looking about the room, she inquired, “Where’ll be the most effective place to stand?” “I’d keep real close to the door if I were you,” Barbara suggested. “Thanks, I will, though I won’t mind at all if you do pelt me with fudge.” “Indeed, not a piece shall you get unless your poetry pleases us,” threatened Margaret. Babs hastened to add, “I choose Betsy’s portion for it’s a foregone conclusion that she won’t get any.”
  • 79. “Silence, young ladies, IF you please.” This in exact imitation of Miss King’s voice and manner. Then making another elaborate bow, Betsy began to read: “There is a young lady named Virg. Who said Life is surely a scourge. I’m so witty and wise That I must editrize Though I’d heaps rather be hearing my dirge.” The listeners laughed while Babs clapped with her thumbnails only. “There’s a senorita, named Marguerita And Oh-a but she’s vera sweeta. Her prida brought to her a fall Once in a thronged study hall. Her prida were her high-heeled feet-a. There is a young damsel named Babs With manners most shocking. She grabs! Whenever there’s candy That’s anywhere handy, The nuttiest pieces she nabs. There is a fair maiden named Sally Who lives in our Sweet Pickle Alley. In front of a mirror You oftenest see her Whenever she has time to dally. There is a most witty young poet Named Betsy, and I’m sure you know it. She can tell by your glances,
  • 80. As you listen in trances, With a bouquet, just waiting to throw it.” Betsy ducked just in time for soft pillows snatched from the window seat were hurled at her. Laughingly she gathered them up and replaced them in a prim row, then she sank down among them as though exhausted. “Believe me, that’s the hardest work I’ve done in my short lifetime. I’d heaps rather shovel coal for a living. I thought I could never think of a word to rhyme with Sally. Luckily we call our corridor Sweet Pickle Alley. That helped some!” Then she interrupted herself to point an accusing finger. “Quick! Look! Caught in the act. Wasn’t I right about Babs? It isn’t yet time to pass the fudge and there she is helping herself to the very piece that I had intended to take, because it’s so bulging full of nuts.” Barbara sprang up, passed the plate and insisted that Betsy take the nutty piece. Then, as they munched, Margaret said, “I’ll never forget the day I wore those high-heeled slippers. Wasn’t I embarrassed, it being a reception for patrons and parents? Common sense heels for me.” The president of The Adventure Club tapped upon the table with her pencil. “Attention, if you please, young ladies,” she said, “there is a matter of importance to be discussed.” The girls looked up wonderingly. “Can you all keep a secret?” Virg asked mysteriously. “Why, of course we can.” This protestingly from Margaret. “Whizzle, what a kweestion? A bottomless well couldn’t be more secretive than I am if I give my word.” Betsy held up her right hand as though taking a vow. “It won’t be hard for me to keep it if I can talk it over with you girls,” Barbara told them. To the surprise of the others Sally rose. “I’d rather not try,” she said, speaking more seriously than usual. “If it leaks out, you’d be sure to think I told, so, if you’ll excuse me, I’d rather not know it.” Virginia rose and placing an arm about the slender girl who had her hand on the door knob, she led her back to the group. “Sally,” she said kindly, “I am sure that you will keep this secret.”
  • 81. The pretty face of the youngest girl glowed with happiness and pride. It was the first time since she had been in that seminary that someone had expressed faith in her. Many a time she had seen groups of girls stop their chattering when she neared and she had felt left out. “They think I’d tell what they’re saying, I suppose,” had been her unhappy conclusion, as she wandered away by herself feeling so alone and unwanted. But this wonderful girl, who was not only president of this little club but also editor of The Manuscript Magazine, actually wanted her to stay and share a real secret. Sally vowed within herself that Virginia would find her worthy of the trust. “We’re all bristling with curiosity, as a porcupine was heard to remark,” Betsy said. “What kind of a secret is it?” Virginia smiled at the mischievous would-be detective, as she replied: “It isn’t anything that will interest you greatly. Yesterday Mrs. Martin sent for me and asked if we girls from the West knew someone who would appreciate a term at Vine Haven as guest. Now that Gwendolyn Laureat has gone, the Tower Room is vacant. I do not know of anyone, but I said that I would ask my closest friends if she wished. Mrs. Martin agreed, but requested that we tell no one else as she never wished the identity of the guest pupil to be generally known.” The girls were silent for a moment thinking over their friends and acquaintances but finally they shook their heads. “It’s just too bad,” Margaret said, “I’m ever so sure there must be some talented girl who would love to have the advantages that this school offers and —” “Such as the refining influence of the members of The Adventure Club,” put in Betsy with a twinkle. “I’ll undertake teaching her up-to- the-minute slang.” Megsy, not heeding the interruption, continued, “and if The Exclusive Three did not know her identity, she ought to be very happy here.” “Woe to her if they do find it out,” Barbara commented. “She might as well pack up and leave that very day.”
  • 82. “Well, since there is no one whom we can suggest, we ourselves will not know who the guest pupil is, as, of course, Mrs. Martin has many sources to draw upon. Boston is full of girls, poor, but talented.” “Now, let’s have our weekly lesson review.” Virginia picked up an Ancient History and in the midst of moans and groans asked the first question. “Babs, you’re improving by the minute,” was Margaret’s comment when the get-ready-for-bed gong pealed through the corridors. “Thanks, greatly! I mean to be a ‘Shining Light’ on the spring exams.” “Wouldn’t you faint right on the spot if you ever saw your name on the Honor Roll board down in the main corridor?” Megsy asked. “Would she? I’ll tell the world!” Betsy answered for her. Then teasingly, “Honestly girls, you may find this hard to believe but I actually saw Babs stop in front of that popular black board every day last week to see if her name is there yet.” Barbara flushed but spunkily protested, “I don’t care if I did. Now that Virg and Margaret are on it, I mean to be, too, if I possibly can.” “Well, you needn’t bite my head off. Sally and I wouldn’t be on it, if we could.” Then Sally surprised them all by saying, “Now that Virginia’s name is there, I’d like ever so much to get my name on it, too.” “How’s that for idolatry?” Betsy began to tease, but Virginia remarked seriously, “Sally, your hardest subject seems to be algebra. I’ll help you, if you wish to study after hours just as Miss Torrence helps me.” “Whee-gee!” Betsy whistled. “If Sally MacLean gets her name on the Honor Roll, it’s me as will faint and I don’t think I’ll ever come to.” When the girls were gone, and the lights had been turned out, Margaret exclaimed, “Oh, Virg, see how beautiful the snowy world is in the moonlight. I’m so glad that Monday is a holiday. Let’s go for a hike if Mrs. Martin will permit. I just adore wading through snow- drifts.”
  • 83. “That would be a great adventure and a new one for me,” said the girl from the desert where snow-drifts are unknown. They were indeed to have an adventure.
  • 84. CHAPTER IV THE FIRST ADVENTURE “A whole holiday and every hour of it free. I feel like some caged bird let loose,” Margaret exclaimed as the five girls from Vine Haven Seminary started away from the school. All were clad in their warmest coats, with leggings, mittens and flying scarfs to match the bright tams that perched jauntily atop of their heads. “And to think that we may hike wherever we wish, on only one condition, and that to report to Mrs. Martin half an hour before lunch,” Barbara chattered. Virginia laughed. “One might think it the greatest kind of a lark just to go outside of the gate,” she said. “I can understand it now, but when I remember how I have galloped all over the desert for miles without thought of keeping within certain boundaries, I don’t wonder that we feel like caged birds.” “Snow birds, then,” Betsy’s merry face beamed out from beneath her cherry colored tam. “Sally surely is. I just adore those white furs. You look like a princess, Sal, stepped out of a fairy book with your golden curls hanging like a mantle about your shoulders.” The others laughed. “Betsy, you aren’t going to burst out into poetry again, are you?” “Not guilty!” that merry maid replied. Then pausing to look about she inquired. “Which way shall we go in search of adventure? Behind us is the sea. The wind is too icily cold to go in that direction. Down below us is the village and beyond that—what?” “Let’s go and find out. Have we time?” Margaret consulted her wrist watch. “Time to burn,” she announced. “It’s only eight-thirty. I’ve walked to the village in half an hour often.”
  • 85. Welcome to Our Bookstore - The Ultimate Destination for Book Lovers Are you passionate about books and eager to explore new worlds of knowledge? At our website, we offer a vast collection of books that cater to every interest and age group. From classic literature to specialized publications, self-help books, and children’s stories, we have it all! Each book is a gateway to new adventures, helping you expand your knowledge and nourish your soul Experience Convenient and Enjoyable Book Shopping Our website is more than just an online bookstore—it’s a bridge connecting readers to the timeless values of culture and wisdom. With a sleek and user-friendly interface and a smart search system, you can find your favorite books quickly and easily. Enjoy special promotions, fast home delivery, and a seamless shopping experience that saves you time and enhances your love for reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebookgate.com