Python Reference Manual
Python Reference Manual
Up: Python Documentation Index Next: Front Matter
Python Reference Manual
Guido van Rossum
Fred L. Drake, Jr., editor
PythonLabs
Email: [email protected]
Release 2.2.1
April 10, 2002
q Front Matter
q Contents
q 1. Introduction
r 1.1 Notation
q 2. Lexical analysis
r 2.1 Line structure
s 2.1.1 Logical lines
s 2.1.2 Physical lines
s 2.1.3 Comments
s 2.1.4 Explicit line joining
s 2.1.5 Implicit line joining
s 2.1.6 Blank lines
s 2.1.7 Indentation
s 2.1.8 Whitespace between tokens
r 2.2 Other tokens
r 2.3 Identifiers and keywords
s 2.3.1 Keywords
s 2.3.2 Reserved classes of identifiers
r 2.4 Literals
s 2.4.1 String literals
s 2.4.2 String literal concatenation
s 2.4.3 Numeric literals
http://davis.lbl.gov/Manuals/PYTHON/ref/ref.html (1 of 4) [3/15/03 11:20:43 AM]
Python Reference Manual
s 2.4.4 Integer and long integer literals
s 2.4.5 Floating point literals
s 2.4.6 Imaginary literals
r 2.5 Operators
r 2.6 Delimiters
q 3. Data model
r 3.1 Objects, values and types
r 3.2 The standard type hierarchy
r 3.3 Special method names
s 3.3.1 Basic customization
s 3.3.2 Customizing attribute access
s 3.3.3 Emulating callable objects
s 3.3.4 Emulating container types
s 3.3.5 Additional methods for emulation of sequence types
s 3.3.6 Emulating numeric types
q 4. Execution model
r 4.1 Code blocks, execution frames, and namespaces
r 4.2 Exceptions
q 5. Expressions
r 5.1 Arithmetic conversions
r 5.2 Atoms
s 5.2.1 Identifiers (Names)
s 5.2.2 Literals
s 5.2.3 Parenthesized forms
s 5.2.4 List displays
s 5.2.5 Dictionary displays
s 5.2.6 String conversions
r 5.3 Primaries
s 5.3.1 Attribute references
s 5.3.2 Subscriptions
s 5.3.3 Slicings
s 5.3.4 Calls
r 5.4 The power operator
r 5.5 Unary arithmetic operations
r 5.6 Binary arithmetic operations
r 5.7 Shifting operations
r 5.8 Binary bit-wise operations
r 5.9 Comparisons
r 5.10 Boolean operations
r 5.11 Expression lists
r 5.12 Summary
http://davis.lbl.gov/Manuals/PYTHON/ref/ref.html (2 of 4) [3/15/03 11:20:43 AM]
Python Reference Manual
q 6. Simple statements
r 6.1 Expression statements
r 6.2 Assert statements
r 6.3 Assignment statements
s 6.3.1 Augmented assignment statements
r 6.4 The pass statement
r 6.5 The del statement
r 6.6 The print statement
r 6.7 The return statement
r 6.8 The yield statement
r 6.9 The raise statement
r 6.10 The break statement
r 6.11 The continue statement
r 6.12 The import statement
r 6.13 The global statement
r 6.14 The exec statement
q 7. Compound statements
r 7.1 The if statement
r 7.2 The while statement
r 7.3 The for statement
r 7.4 The try statement
r 7.5 Function definitions
r 7.6 Class definitions
q 8. Top-level components
r 8.1 Complete Python programs
r 8.2 File input
r 8.3 Interactive input
r 8.4 Expression input
q A. Future statements and nested scopes
r A.1 Future statements
r A.2 __future__ -- Future statement definitions
r A.3 Nested scopes
s A.3.1 Definitions and rules
s A.3.2 Interaction with dynamic features
q B. History and License
r B.1 History of the software
r B.2 Terms and conditions for accessing or otherwise using Python
q Index
q About this document ...
http://davis.lbl.gov/Manuals/PYTHON/ref/ref.html (3 of 4) [3/15/03 11:20:43 AM]
Python Reference Manual
Python Reference Manual
Up: Python Documentation Index Next: Front Matter
Release 2.2.1, documentation updated on April 10, 2002.
See About this document... for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/ref/ref.html (4 of 4) [3/15/03 11:20:43 AM]
Python 2.2.1 Documentation - April 10, 2002
Python Documentation
Python Documentation
Release 2.2.1
April 10, 2002
q Tutorial q What's New in Python
(start here) (changes since the last major
release)
q Global Module Index q Language Reference
(for quick access to all documentation) (for language lawyers)
q Library Reference q Extending and Embedding
(keep this under your pillow) (tutorial for C/C++ programmers)
q Macintosh Module Reference q Python/C API
(this too, if you use a Macintosh) (reference for C/C++ programmers)
q Installing Python Modules q Documenting Python
(for administrators) (information for documentation
authors)
q Distributing Python Modules
(for developers and packagers)
q Documentation Central q Python How-To Guides
(for everyone) (special topics)
See About the Python Documentation for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/index.html [3/15/03 11:20:46 AM]
Front Matter
Python Reference Manual
Previous: Python Reference Manual Up: Python Reference Manual Next: Contents
Front Matter
Copyright © 2001 Python Software Foundation. All rights reserved.
Copyright © 2000 BeOpen.com. All rights reserved.
Copyright © 1995-2000 Corporation for National Research Initiatives. All rights
reserved.
Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved.
See the end of this document for complete license and permissions information.
Abstract:
Python is an interpreted, object-oriented, high-level programming language with
dynamic semantics. Its high-level built in data structures, combined with dynamic
typing and dynamic binding, make it very attractive for rapid application
development, as well as for use as a scripting or glue language to connect existing
components together. Python's simple, easy to learn syntax emphasizes readability and
therefore reduces the cost of program maintenance. Python supports modules and
packages, which encourages program modularity and code reuse. The Python
interpreter and the extensive standard library are available in source or binary form
without charge for all major platforms, and can be freely distributed.
This reference manual describes the syntax and ``core semantics'' of the language. It is
terse, but attempts to be exact and complete. The semantics of non-essential built-in
object types and of the built-in functions and modules are described in the Python
Library Reference. For an informal introduction to the language, see the Python
Tutorial. For C or C++ programmers, two additional manuals exist: Extending and
Embedding the Python Interpreter describes the high-level picture of how to write a
Python extension module, and the Python/C API Reference Manual describes the
interfaces available to C/C++ programmers in detail.
http://davis.lbl.gov/Manuals/PYTHON/ref/front.html (1 of 2) [3/15/03 11:20:48 AM]
Front Matter
Python Reference Manual
Previous: Python Reference Manual Up: Python Reference Manual Next: Contents
Release 2.2.1, documentation updated on April 10, 2002.
See About this document... for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/ref/front.html (2 of 2) [3/15/03 11:20:48 AM]
Contents
Python Reference Manual
Previous: Front Matter Up: Python Reference Manual Next: 1. Introduction
Contents
q Front Matter
q 1. Introduction
r 1.1 Notation
q 2. Lexical analysis
r 2.1 Line structure
s 2.1.1 Logical lines
s 2.1.2 Physical lines
s 2.1.3 Comments
s 2.1.4 Explicit line joining
s 2.1.5 Implicit line joining
s 2.1.6 Blank lines
s 2.1.7 Indentation
s 2.1.8 Whitespace between tokens
r 2.2 Other tokens
r 2.3 Identifiers and keywords
s 2.3.1 Keywords
s 2.3.2 Reserved classes of identifiers
r 2.4 Literals
s 2.4.1 String literals
s 2.4.2 String literal concatenation
s 2.4.3 Numeric literals
s 2.4.4 Integer and long integer literals
s 2.4.5 Floating point literals
s 2.4.6 Imaginary literals
r 2.5 Operators
r 2.6 Delimiters
q 3. Data model
r 3.1 Objects, values and types
r 3.2 The standard type hierarchy
r 3.3 Special method names
s 3.3.1 Basic customization
s 3.3.2 Customizing attribute access
http://davis.lbl.gov/Manuals/PYTHON/ref/contents.html (1 of 3) [3/15/03 11:20:50 AM]
Contents
s 3.3.3 Emulating callable objects
s 3.3.4 Emulating container types
s 3.3.5 Additional methods for emulation of sequence types
s 3.3.6 Emulating numeric types
q 4. Execution model
r 4.1 Code blocks, execution frames, and namespaces
r 4.2 Exceptions
q 5. Expressions
r 5.1 Arithmetic conversions
r 5.2 Atoms
s 5.2.1 Identifiers (Names)
s 5.2.2 Literals
s 5.2.3 Parenthesized forms
s 5.2.4 List displays
s 5.2.5 Dictionary displays
s 5.2.6 String conversions
r 5.3 Primaries
s 5.3.1 Attribute references
s 5.3.2 Subscriptions
s 5.3.3 Slicings
s 5.3.4 Calls
r 5.4 The power operator
r 5.5 Unary arithmetic operations
r 5.6 Binary arithmetic operations
r 5.7 Shifting operations
r 5.8 Binary bit-wise operations
r 5.9 Comparisons
r 5.10 Boolean operations
r 5.11 Expression lists
r 5.12 Summary
q 6. Simple statements
r 6.1 Expression statements
r 6.2 Assert statements
r 6.3 Assignment statements
s 6.3.1 Augmented assignment statements
r 6.4 The pass statement
r 6.5 The del statement
r 6.6 The print statement
r 6.7 The return statement
r 6.8 The yield statement
r 6.9 The raise statement
http://davis.lbl.gov/Manuals/PYTHON/ref/contents.html (2 of 3) [3/15/03 11:20:50 AM]
Contents
r 6.10 The break statement
r 6.11 The continue statement
r 6.12 The import statement
r 6.13 The global statement
r 6.14 The exec statement
q 7. Compound statements
r 7.1 The if statement
r 7.2 The while statement
r 7.3 The for statement
r 7.4 The try statement
r 7.5 Function definitions
r 7.6 Class definitions
q 8. Top-level components
r 8.1 Complete Python programs
r 8.2 File input
r 8.3 Interactive input
r 8.4 Expression input
q A. Future statements and nested scopes
r A.1 Future statements
r A.2 __future__ -- Future statement definitions
r A.3 Nested scopes
s A.3.1 Definitions and rules
s A.3.2 Interaction with dynamic features
q B. History and License
r B.1 History of the software
r B.2 Terms and conditions for accessing or otherwise using Python
q Index
q About this document ...
Python Reference Manual
Previous: Front Matter Up: Python Reference Manual Next: 1. Introduction
Release 2.2.1, documentation updated on April 10, 2002.
See About this document... for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/ref/contents.html (3 of 3) [3/15/03 11:20:50 AM]
Index
Python Reference Manual
Previous: B.2 Terms and conditions Up: Python Reference Manual Next: About this
document ...
Index
_|a|b|c|d|e|f|g|h|i|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z
_ (underscore)
__abs__() (numeric object method) __int__() (numeric object method)
__add__() (numeric object method) __invert__() (numeric object method)
__add__() (sequence object method) __ior__() (numeric object method)
__and__() (numeric object method) __ipow__() (numeric object method)
__bases__ (class attribute) __irshift__() (numeric object method)
__builtin__ (built-in module), [Link], __isub__() (numeric object method)
[Link] __iter__() (container object method)
__builtins__ __ixor__() (numeric object method)
__call__() (object method), [Link] __le__() (object method)
__class__ (instance attribute) __len__() (container object method)
__cmp__() (object method), [Link] __len__() (mapping object method)
__coerce__() (numeric object method), __long__() (numeric object method)
[Link] __lshift__() (numeric object method)
__complex__() (numeric object method) __lt__() (object method)
__contains__() (container object method) __main__ (built-in module), [Link],
__contains__() (mapping object method) [Link], [Link]
__contains__() (sequence object method) __mod__() (numeric object method)
__debug__ __module__ (class attribute)
__del__() (object method) __mul__() (numeric object method)
__delattr__() (object method) __mul__() (sequence object method)
__delitem__() (container object method) __name__ (class attribute)
__delslice__() (sequence object method) __name__ (function attribute)
__dict__ (class attribute) __name__ (module attribute)
__dict__ (function attribute) __ne__() (object method)
__dict__ (instance attribute), [Link] __neg__() (numeric object method)
__dict__ (module attribute) __nonzero__() (object method), [Link]
http://davis.lbl.gov/Manuals/PYTHON/ref/genindex.html (1 of 18) [3/15/03 11:20:57 AM]
Index
__div__() (numeric object method) __oct__() (numeric object method)
__divmod__() (numeric object method) __or__() (numeric object method)
__doc__ (class attribute) __pos__() (numeric object method)
__doc__ (function attribute) __pow__() (numeric object method)
__doc__ (module attribute) __radd__() (numeric object method)
__eq__() (object method) __radd__() (sequence object method)
__file__ (module attribute) __rand__() (numeric object method)
__float__() (numeric object method) __rcmp__() (object method)
__floordiv__() (numeric object method) __rdiv__() (numeric object method)
__future__ (standard module) __rdivmod__() (numeric object method)
__ge__() (object method) __repr__() (object method)
__getattr__() (object method) __rlshift__() (numeric object method)
__getitem__() (container object method) __rmod__() (numeric object method)
__getitem__() (mapping object method) __rmul__() (numeric object method)
__getslice__() (sequence object method) __rmul__() (sequence object method)
__gt__() (object method) __ror__() (numeric object method)
__hash__() (object method) __rpow__() (numeric object method)
__hex__() (numeric object method) __rrshift__() (numeric object method)
__iadd__() (numeric object method) __rshift__() (numeric object method)
__iadd__() (sequence object method) __rsub__() (numeric object method)
__iand__() (numeric object method) __rxor__() (numeric object method)
__idiv__() (numeric object method) __setattr__() (object method), [Link]
__ilshift__() (numeric object method) __setitem__() (container object method)
__imod__() (numeric object method) __setslice__() (sequence object method)
__import__() (built-in function) __str__() (object method)
__imul__() (numeric object method) __sub__() (numeric object method)
__imul__() (sequence object method) __truediv__() (numeric object method)
__init__() (object method), [Link] __xor__() (numeric object method)
__init__.py
A
http://davis.lbl.gov/Manuals/PYTHON/ref/genindex.html (2 of 18) [3/15/03 11:20:57 AM]
Index
abs() (built-in function) assignment (continued)
addition class instance attribute
and slicing
statement, [Link]
bit-wise subscription
and operator target list
anonmymous
atom
function attribute
append() (sequence object method) assignment, [Link]
argument assignment, class
assignment, class instance
function class
arithmetic class instance
deletion
conversion generic special
operation, binary reference
operation, unary special
array (standard module) AttributeError exception
ASCII, [Link], [Link], [Link], [Link], augmented
[Link]
assert statement assignment
AssertionError exception
assertions
debugging
assignment
attribute, [Link]
augmented
class attribute
B
http://davis.lbl.gov/Manuals/PYTHON/ref/genindex.html (3 of 18) [3/15/03 11:20:57 AM]
Index BNF, [Link]
Boolean
back-quotes, [Link]
backslash character operation
backward break statement, [Link], [Link], [Link],
[Link]
quotes, [Link] bsddb (standard module)
binary built-in
arithmetic operation method
bit-wise operation module
binding name
global name built-in function
name, [Link], [Link], [Link], call
[Link], [Link], [Link] built-in function object, [Link]
bit-wise built-in method
and call
operation, binary built-in method object, [Link]
operation, unary byte
or bytecode
xor
blank line
block
code
C
C co_filename (code object attribute)
language, [Link], [Link], [Link] co_firstlineno (code object attribute)
call co_flags (code object attribute)
built-in function co_freevars (code object attribute)
built-in method co_lnotab (code object attribute)
class instance co_name (code object attribute)
class object, [Link], [Link], [Link] co_names (code object attribute)
function, [Link], [Link] co_nlocals (code object attribute)
instance, [Link] co_stacksize (code object attribute)
method co_varnames (code object attribute)
procedure code
user-defined function
callable object, [Link] block
chaining code block, [Link], [Link]
code object
comparisons comma
http://davis.lbl.gov/Manuals/PYTHON/ref/genindex.html (4 of 18) [3/15/03 11:20:57 AM]
Index
character, [Link], [Link] trailing, [Link]
character set command line
chr() (built-in function), [Link] comment
class comparison
string
attribute comparisons
attribute assignment chaining
constructor compile() (built-in function)
definition, [Link] complex
instance
name number
class instance complex() (built-in function)
attribute complex literal
attribute assignment complex object
call compound
class instance object, [Link], [Link],
[Link] statement
class object, [Link], [Link], [Link] comprehensions
call, [Link], [Link], [Link]
class statement list, [Link]
clause constant
clear() (mapping object method) constructor
cmp() (built-in function)
co_argcount (code object attribute) class
co_cellvars (code object attribute) container, [Link]
co_code (code object attribute) continue statement, [Link], [Link], [Link],
co_consts (code object attribute) [Link]
conversion
arithmetic
string, [Link], [Link]
copy() (mapping object method)
count() (sequence object method)
D
http://davis.lbl.gov/Manuals/PYTHON/ref/genindex.html (5 of 18) [3/15/03 11:20:58 AM]
Index delete
deletion
dangling
else attribute
target
data target list
type delimiters
type, immutable destructor, [Link]
datum dictionary
dbm (standard module) display
debugging dictionary object, [Link], [Link], [Link],
[Link], [Link]
assertions display
decimal literal dictionary
DEDENT token, [Link] list
def statement tuple
default division
divmod() (built-in function), [Link]
parameter value documentation string
definition
class, [Link]
function, [Link]
del statement, [Link], [Link]
E
EBCDIC exception (continued)
elif raising
RuntimeError
keyword StopIteration
Ellipsis SyntaxError, [Link]
Ellipsis object TypeError
else ValueError
ZeroDivisionError
dangling
keyword, [Link], [Link], [Link], exception handler
[Link] exclusive
empty
list or
tuple, [Link] exec statement, [Link], [Link]
error handling execfile() (built-in function)
errors execution
escape sequence
eval() (built-in function), [Link], [Link] frame, [Link], [Link]
exc_info (in module sys) restricted
stack
http://davis.lbl.gov/Manuals/PYTHON/ref/genindex.html (6 of 18) [3/15/03 11:20:58 AM]
Index
exc_traceback (in module sys), [Link] execution model
exc_type (in module sys) expression
exc_value (in module sys) lambda
except list, [Link], [Link]
statement
keyword extended
exception, [Link]
AssertionError slicing
AttributeError extended print statement
handler extension
ImportError, [Link]
NameError filename
module
F
f_back (frame attribute) form
f_builtins (frame attribute) lambda, [Link]
f_code (frame attribute)
f_exc_traceback (frame attribute) frame
f_exc_type (frame attribute) execution, [Link], [Link]
f_exc_value (frame attribute)
f_globals (frame attribute) frame object
f_lasti (frame attribute) from
f_lineno (frame attribute)
f_locals (frame attribute) keyword, [Link]
f_restricted (frame attribute) from statement, [Link]
f_trace (frame attribute) func_code (function attribute)
file object, [Link] func_defaults (function attribute)
filename func_dict (function attribute)
func_doc (function attribute)
extension func_globals (function attribute)
finally function
keyword, [Link], [Link], [Link] anonmymous
float() (built-in function) argument
floating point call, [Link], [Link]
call, user-defined
number definition, [Link]
floating point literal generator
floating point object name
for statement, [Link], [Link] user-defined
function object, [Link], [Link], [Link],
http://davis.lbl.gov/Manuals/PYTHON/ref/genindex.html (7 of 18) [3/15/03 11:20:58 AM]
Index
[Link]
future
statement
G global (continued)
name binding
garbage collection namespace, [Link]
gdbm (standard module)
generator global statement, [Link], [Link], [Link],
[Link], [Link], [Link]
function, [Link] globals() (built-in function)
iterator, [Link] grammar
generic grouping
special attribute
get() (mapping object method)
global
name
H hex() (built-in function)
hexadecimal literal
handle an exception hierarchical
handler
module names
exception hierarchy
has_key() (mapping object method)
hash() (built-in function) type
hash character
I
http://davis.lbl.gov/Manuals/PYTHON/ref/genindex.html (8 of 18) [3/15/03 11:20:58 AM]
Index initialization
module
id() (built-in function)
identifier, [Link] input
identity raw
input() (built-in function)
test insert() (sequence object method)
identity of an object instance
if statement
im_class (method attribute) call, [Link]
im_func (method attribute), [Link] class
im_self (method attribute), [Link] instance object, [Link], [Link], [Link]
imaginary literal int() (built-in function)
immutable integer
representation
data type integer literal
object, [Link] integer object
immutable object, [Link] interactive mode
immutable sequence object internal type
import statement, [Link] interpreter
ImportError exception, [Link] inversion
importing invocation
module is not operator
in is operator
keyword item
in operator sequence
inclusive string
or item selection
INDENT token items() (mapping object method)
indentation
index() (sequence object method)
index operation
inheritance
K
http://davis.lbl.gov/Manuals/PYTHON/ref/genindex.html (9 of 18) [3/15/03 11:20:58 AM]
Index keyword (continued)
else, [Link], [Link], [Link], [Link]
key except
key/datum pair finally, [Link], [Link], [Link]
keys() (mapping object method) from, [Link]
keyword in
elif
L
lambda list (continued)
expression display
form, [Link] empty
expression, [Link], [Link]
language target, [Link]
C, [Link], [Link], [Link]
Pascal list object, [Link], [Link], [Link], [Link],
[Link]
last_traceback (in module sys) literal, [Link]
leading whitespace local
len() (built-in function), [Link], [Link]
lexical analysis namespace
lexical definitions locals() (built-in function)
line continuation logical line
line joining, [Link] long() (built-in function)
line structure long integer literal
list long integer object
loop
assignment, target
comprehensions, [Link] over mutable sequence
deletion target statement, [Link], [Link], [Link]
loop control
target
M
http://davis.lbl.gov/Manuals/PYTHON/ref/genindex.html (10 of 18) [3/15/03 11:20:58 AM]
Index
makefile() (socket method) module (continued)
mangling name
names, hierarchical
name namespace
mapping object, [Link], [Link], [Link] search path
membership user-defined
test module object, [Link]
method modules (in module sys)
modulo
built-in multiplication
call mutable object, [Link], [Link], [Link]
user-defined mutable sequence
method object, [Link], [Link]
minus loop over
module mutable sequence object
built-in
extension
importing
initialization
N
name, [Link] negation
binding, [Link], [Link], [Link], [Link], nested
[Link], [Link]
binding, global scopes
built-in newline
class
function suppression
global NEWLINE token, [Link]
mangling None, [Link]
module None object
rebinding, [Link] not in operator
unbinding, [Link] not operator
NameError exception notation
names NotImplemented
NotImplemented object
hierarchical module null
private
namespace, [Link] operation
number
complex
floating point
http://davis.lbl.gov/Manuals/PYTHON/ref/genindex.html (11 of 18) [3/15/03 11:20:58 AM]
Index numeric literal
numeric object, [Link]
global, [Link]
local
module
O
object object (continued)
built-in function, [Link] traceback, [Link], [Link]
built-in method, [Link] tuple, [Link], [Link], [Link]
callable, [Link] unicode
class, [Link], [Link], [Link] user-defined function, [Link],
class instance, [Link], [Link], [Link] [Link]
code user-defined method
complex oct() (built-in function)
dictionary, [Link], [Link], [Link], [Link], octal literal
[Link] open() (built-in function)
Ellipsis operation
file, [Link] binary arithmetic
floating point binary bit-wise
frame Boolean
function, [Link], [Link], [Link], [Link] null
immutable, [Link], [Link] shifting
immutable sequence unary arithmetic
instance, [Link], [Link], [Link] unary bit-wise
integer operator
list, [Link], [Link], [Link], [Link], [Link] and
long integer in
mapping, [Link], [Link], [Link] is
method, [Link], [Link] is not
module, [Link] not
mutable, [Link], [Link] not in
mutable sequence or
None precedence
NotImplemented operators
numeric, [Link] or
plain integer bit-wise
recursive exclusive
http://davis.lbl.gov/Manuals/PYTHON/ref/genindex.html (12 of 18) [3/15/03 11:20:58 AM]
Index
sequence, [Link], [Link], [Link], [Link], inclusive
[Link], [Link] or operator
slice ord() (built-in function), [Link], [Link]
string, [Link], [Link] output, [Link]
standard, [Link]
OverflowError (built-in exception)
P plus
pop() (sequence object method)
packages popen() (in module os)
parameter pow() (built-in function), [Link], [Link],
[Link]
value, default precedence
parenthesized form
parser operator
Pascal primary
print statement, [Link]
language private
pass statement
path names
procedure
module search
physical line, [Link], [Link] call
plain integer literal program
plain integer object
Q quotes (continued)
reverse, [Link]
quotes
backward, [Link]
R
http://davis.lbl.gov/Manuals/PYTHON/ref/genindex.html (13 of 18) [3/15/03 11:20:58 AM]
Index reference counting
remove() (sequence object method)
raise an exception repr() (built-in function), [Link], [Link]
raise statement representation
raising
integer
exception reserved word
range() (built-in function) restricted
raw input
raw string execution
raw_input() (built-in function) return statement, [Link], [Link]
readline() (file method) reverse
rebinding
quotes, [Link]
name, [Link] reverse() (sequence object method)
recursive object RuntimeError exception
reference
attribute
S
scopes statement (continued)
nested loop, [Link], [Link], [Link]
pass
search print, [Link]
path, module raise
return, [Link], [Link]
sequence simple
item try, [Link]
while, [Link], [Link]
sequence object, [Link], [Link], [Link], yield
[Link], [Link], [Link]
shifting statement grouping
stderr (in module sys)
operation stdin (in module sys)
simple stdio
stdout (in module sys), [Link]
statement step (slice object attribute), [Link]
singleton stop (slice object attribute), [Link]
StopIteration exception
tuple str() (built-in function), [Link]
slice string
slice() (built-in function)
slice object
slicing, [Link], [Link]
assignment
extended
sort() (sequence object method)
http://davis.lbl.gov/Manuals/PYTHON/ref/genindex.html (14 of 18) [3/15/03 11:20:58 AM]
Index
space comparison
special conversion, [Link], [Link]
item
attribute Unicode
attribute, generic string literal
stack string object, [Link], [Link]
execution subscription, [Link], [Link], [Link]
trace assignment
standard subtraction
output, [Link] suite
Standard C suppression
standard input newline
start (slice object attribute), [Link] syntax, [Link]
statement SyntaxError exception, [Link]
assert sys (built-in module), [Link], [Link],
assignment, [Link] [Link]
assignment, augmented sys.exc_info
break, [Link], [Link], [Link], sys.exc_traceback
[Link] sys.last_traceback
class sys.modules
compound sys.stderr
continue, [Link], [Link], [Link], sys.stdin
[Link] sys.stdout
def
del, [Link], [Link]
exec, [Link], [Link]
expression
for, [Link], [Link]
from, [Link]
future
global, [Link], [Link], [Link],
[Link], [Link], [Link]
if
import, [Link]
T
http://davis.lbl.gov/Manuals/PYTHON/ref/genindex.html (15 of 18) [3/15/03 11:20:58 AM]
Index traceback object, [Link], [Link]
trailing
tab
target comma, [Link]
deletion triple-quoted string
list, [Link] try statement, [Link]
list assignment tuple
list, deletion
loop control display
tb_frame (traceback attribute) empty, [Link]
tb_lasti (traceback attribute) singleton
tb_lineno (traceback attribute) tuple object, [Link], [Link], [Link]
tb_next (traceback attribute) type
termination model data
test hierarchy
immutable data
identity type() (built-in function)
membership type of an object
token TypeError exception
trace types, internal
stack
U unreachable object
unrecognized escape sequence
unary update() (mapping object method)
arithmetic operation user-defined
bit-wise operation
function
unbinding function call
name, [Link] method
module
unichr() (built-in function) user-defined function object, [Link],
Unicode [Link]
unicode() (built-in function) user-defined method object
Unicode Consortium
unicode object
UNIX
V
http://davis.lbl.gov/Manuals/PYTHON/ref/genindex.html (16 of 18) [3/15/03 11:20:58 AM]
Index values
writing, [Link]
value
default parameter values() (mapping object method)
value of an object
ValueError exception
W writing
values, [Link]
while statement, [Link], [Link]
whitespace
X
xor
bit-wise
Y
yield statement
Z
ZeroDivisionError exception
http://davis.lbl.gov/Manuals/PYTHON/ref/genindex.html (17 of 18) [3/15/03 11:20:58 AM]
Index
Python Reference Manual
Previous: B.2 Terms and conditions Up: Python Reference Manual Next: About this
document ...
Release 2.2.1, documentation updated on April 10, 2002.
See About this document... for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/ref/genindex.html (18 of 18) [3/15/03 11:20:58 AM]
1. Introduction
Python Reference Manual
Previous: Contents Up: Python Reference Manual Next: 1.1 Notation
1. Introduction
This reference manual describes the Python programming language. It is not intended
as a tutorial.
While I am trying to be as precise as possible, I chose to use English rather than
formal specifications for everything except syntax and lexical analysis. This should
make the document more understandable to the average reader, but will leave room for
ambiguities. Consequently, if you were coming from Mars and tried to re-implement
Python from this document alone, you might have to guess things and in fact you
would probably end up implementing quite a different language. On the other hand, if
you are using Python and wonder what the precise rules about a particular area of the
language are, you should definitely be able to find them here. If you would like to see
a more formal definition of the language, maybe you could volunteer your time -- or
invent a cloning machine :-).
It is dangerous to add too many implementation details to a language reference
document -- the implementation may change, and other implementations of the same
language may work differently. On the other hand, there is currently only one Python
implementation in widespread use (although a second one now exists!), and its
particular quirks are sometimes worth being mentioned, especially where the
implementation imposes additional limitations. Therefore, you'll find short
``implementation notes'' sprinkled throughout the text.
Every Python implementation comes with a number of built-in and standard modules.
These are not documented here, but in the separate Python Library Reference
document. A few built-in modules are mentioned when they interact in a significant
way with the language definition.
Subsections
q 1.1 Notation
http://davis.lbl.gov/Manuals/PYTHON/ref/introduction.html (1 of 2) [3/15/03 11:21:00 AM]
1. Introduction
Python Reference Manual
Previous: Contents Up: Python Reference Manual Next: 1.1 Notation
Release 2.2.1, documentation updated on April 10, 2002.
See About this document... for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/ref/introduction.html (2 of 2) [3/15/03 11:21:00 AM]
1.1 Notation
Python Reference Manual
Previous: 1. Introduction Up: 1. Introduction Next: 2. Lexical analysis
1.1 Notation
The descriptions of lexical analysis and syntax use a modified BNF grammar notation.
This uses the following style of definition:
name: lc_letter (lc_letter | "_")*
lc_letter: "a"..."z"
The first line says that a name is an lc_letter followed by a sequence of zero or
more lc_letters and underscores. An lc_letter in turn is any of the single
characters "a" through "z". (This rule is actually adhered to for the names defined in
lexical and grammar rules in this document.)
Each rule begins with a name (which is the name defined by the rule) and a colon. A
vertical bar (|) is used to separate alternatives; it is the least binding operator in this
notation. A star (*) means zero or more repetitions of the preceding item; likewise, a
plus (+) means one or more repetitions, and a phrase enclosed in square brackets ([
]) means zero or one occurrences (in other words, the enclosed phrase is optional).
The * and + operators bind as tightly as possible; parentheses are used for grouping.
Literal strings are enclosed in quotes. White space is only meaningful to separate
tokens. Rules are normally contained on a single line; rules with many alternatives
may be formatted alternatively with each line after the first beginning with a vertical
bar.
In lexical definitions (as the example above), two more conventions are used: Two
literal characters separated by three dots mean a choice of any single character in the
given (inclusive) range of ASCII characters. A phrase between angular brackets
(<...>) gives an informal description of the symbol defined; e.g., this could be used
to describe the notion of `control character' if needed.
Even though the notation used is almost the same, there is a big difference between the
meaning of lexical and syntactic definitions: a lexical definition operates on the
individual characters of the input source, while a syntax definition operates on the
stream of tokens generated by the lexical analysis. All uses of BNF in the next chapter
(``Lexical Analysis'') are lexical definitions; uses in subsequent chapters are syntactic
definitions.
http://davis.lbl.gov/Manuals/PYTHON/ref/notation.html (1 of 2) [3/15/03 11:21:02 AM]
1.1 Notation
Python Reference Manual
Previous: 1. Introduction Up: 1. Introduction Next: 2. Lexical analysis
Release 2.2.1, documentation updated on April 10, 2002.
See About this document... for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/ref/notation.html (2 of 2) [3/15/03 11:21:02 AM]
2. Lexical analysis
Python Reference Manual
Previous: 1.1 Notation Up: Python Reference Manual Next: 2.1 Line structure
2. Lexical analysis
A Python program is read by a parser. Input to the parser is a stream of tokens,
generated by the lexical analyzer. This chapter describes how the lexical analyzer
breaks a file into tokens.
Python uses the 7-bit ASCII character set for program text and string literals. 8-bit
characters may be used in string literals and comments but their interpretation is
platform dependent; the proper way to insert 8-bit characters in string literals is by
using octal or hexadecimal escape sequences.
The run-time character set depends on the I/O devices connected to the program but is
generally a superset of ASCII.
Future compatibility note: It may be tempting to assume that the character set for 8-
bit characters is ISO Latin-1 (an ASCII superset that covers most western languages
that use the Latin alphabet), but it is possible that in the future Unicode text editors
will become common. These generally use the UTF-8 encoding, which is also an
ASCII superset, but with very different use for the characters with ordinals 128-255.
While there is no consensus on this subject yet, it is unwise to assume either Latin-1 or
UTF-8, even though the current implementation appears to favor Latin-1. This applies
both to the source character set and the run-time character set.
Subsections
q 2.1 Line structure
r 2.1.1 Logical lines
r 2.1.2 Physical lines
r 2.1.3 Comments
r 2.1.4 Explicit line joining
r 2.1.5 Implicit line joining
r 2.1.6 Blank lines
r 2.1.7 Indentation
r 2.1.8 Whitespace between tokens
q 2.2 Other tokens
http://davis.lbl.gov/Manuals/PYTHON/ref/lexical.html (1 of 2) [3/15/03 11:21:04 AM]
2. Lexical analysis
q 2.3 Identifiers and keywords
r 2.3.1 Keywords
r 2.3.2 Reserved classes of identifiers
q 2.4 Literals
r 2.4.1 String literals
r 2.4.2 String literal concatenation
r 2.4.3 Numeric literals
r 2.4.4 Integer and long integer literals
r 2.4.5 Floating point literals
r 2.4.6 Imaginary literals
q 2.5 Operators
q 2.6 Delimiters
Python Reference Manual
Previous: 1.1 Notation Up: Python Reference Manual Next: 2.1 Line structure
Release 2.2.1, documentation updated on April 10, 2002.
See About this document... for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/ref/lexical.html (2 of 2) [3/15/03 11:21:04 AM]
2.1 Line structure
Python Reference Manual
Previous: 2. Lexical analysis Up: 2. Lexical analysis Next: 2.1.1 Logical lines
2.1 Line structure
A Python program is divided into a number of logical lines.
Subsections
q 2.1.1 Logical lines
q 2.1.2 Physical lines
q 2.1.3 Comments
q 2.1.4 Explicit line joining
q 2.1.5 Implicit line joining
q 2.1.6 Blank lines
q 2.1.7 Indentation
q 2.1.8 Whitespace between tokens
Python Reference Manual
Previous: 2. Lexical analysis Up: 2. Lexical analysis Next: 2.1.1 Logical lines
Release 2.2.1, documentation updated on April 10, 2002.
See About this document... for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/ref/line-structure.html [3/15/03 11:21:06 AM]
2.1.1 Logical lines
Python Reference Manual
Previous: 2.1 Line structure Up: 2.1 Line structure Next: 2.1.2 Physical lines
2.1.1 Logical lines
The end of a logical line is represented by the token NEWLINE. Statements cannot
cross logical line boundaries except where NEWLINE is allowed by the syntax (e.g.,
between statements in compound statements). A logical line is constructed from one
or more physical lines by following the explicit or implicit line joining rules.
Python Reference Manual
Previous: 2.1 Line structure Up: 2.1 Line structure Next: 2.1.2 Physical lines
Release 2.2.1, documentation updated on April 10, 2002.
See About this document... for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/ref/logical.html [3/15/03 11:21:08 AM]
2.1.2 Physical lines
Python Reference Manual
Previous: 2.1.1 Logical lines Up: 2.1 Line structure Next: 2.1.3 Comments
2.1.2 Physical lines
A physical line ends in whatever the current platform's convention is for terminating
lines. On Unix, this is the ASCII LF (linefeed) character. On DOS/Windows, it is the
ASCII sequence CR LF (return followed by linefeed). On Macintosh, it is the ASCII
CR (return) character.
Python Reference Manual
Previous: 2.1.1 Logical lines Up: 2.1 Line structure Next: 2.1.3 Comments
Release 2.2.1, documentation updated on April 10, 2002.
See About this document... for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/ref/physical.html [3/15/03 11:21:11 AM]
2.1.3 Comments
Python Reference Manual
Previous: 2.1.2 Physical lines Up: 2.1 Line structure Next: 2.1.4 Explicit line joining
2.1.3 Comments
A comment starts with a hash character (#) that is not part of a string literal, and ends
at the end of the physical line. A comment signifies the end of the logical line unless
the implicit line joining rules are invoked. Comments are ignored by the syntax; they
are not tokens.
Python Reference Manual
Previous: 2.1.2 Physical lines Up: 2.1 Line structure Next: 2.1.4 Explicit line joining
Release 2.2.1, documentation updated on April 10, 2002.
See About this document... for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/ref/comments.html [3/15/03 11:21:13 AM]
2.1.4 Explicit line joining
Python Reference Manual
Previous: 2.1.3 Comments Up: 2.1 Line structure Next: 2.1.5 Implicit line joining
2.1.4 Explicit line joining
Two or more physical lines may be joined into logical lines using backslash characters (\), as follows: when a
physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following
forming a single logical line, deleting the backslash and the following end-of-line character. For example:
if 1900 < year < 2100 and 1 <= month <= 12 \ # Looks like a valid date
and 1 <= day <= 31 and 0 <= hour < 24 \
and 0 <= minute < 60 and 0 <= second < 60:
return 1
A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does
not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical
lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.
Python Reference Manual
Previous: 2.1.3 Comments Up: 2.1 Line structure Next: 2.1.5 Implicit line joining
Release 2.2.1, documentation updated on April 10, 2002.
See About this document... for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/ref/explicit-joining.html [3/15/03 11:21:15 AM]
2.1.5 Implicit line joining
Python Reference Manual
Previous: 2.1.4 Explicit line joining Up: 2.1 Line structure Next: 2.1.6 Blank lines
2.1.5 Implicit line joining
Expressions in parentheses, square brackets or curly braces can be split over more than one physical line
without using backslashes. For example:
month_names = ['Januari', 'Februari', 'Maart', # These are the
# Dutch names
'April', 'Mei', 'Juni', # for the months
# of the year
'Juli', 'Augustus', 'September',
'Oktober', 'November', 'December']
Implicitly continued lines can carry comments. The indentation of the continuation lines is not important.
Blank continuation lines are allowed. There is no NEWLINE token between implicit continuation lines.
Implicitly continued lines can also occur within triple-quoted strings (see below); in that case they cannot
carry comments.
Python Reference Manual
Previous: 2.1.4 Explicit line joining Up: 2.1 Line structure Next: 2.1.6 Blank lines
Release 2.2.1, documentation updated on April 10, 2002.
See About this document... for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/ref/implicit-joining.html [3/15/03 11:21:18 AM]
2.1.6 Blank lines
Python Reference Manual
Previous: 2.1.5 Implicit line joining Up: 2.1 Line structure Next: 2.1.7 Indentation
2.1.6 Blank lines
A logical line that contains only spaces, tabs, formfeeds and possibly a comment, is
ignored (i.e., no NEWLINE token is generated). During interactive input of
statements, handling of a blank line may differ depending on the implementation of
the read-eval-print loop. In the standard implementation, an entirely blank logical line
(i.e. one containing not even whitespace or a comment) terminates a multi-line
statement.
Python Reference Manual
Previous: 2.1.5 Implicit line joining Up: 2.1 Line structure Next: 2.1.7 Indentation
Release 2.2.1, documentation updated on April 10, 2002.
See About this document... for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/ref/blank-lines.html [3/15/03 11:21:23 AM]
2.1.7 Indentation
Python Reference Manual
Previous: 2.1.6 Blank lines Up: 2.1 Line structure Next: 2.1.8 Whitespace between tokens
2.1.7 Indentation
Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the
indentation level of the line, which in turn is used to determine the grouping of statements.
First, tabs are replaced (from left to right) by one to eight spaces such that the total number of
characters up to and including the replacement is a multiple of eight (this is intended to be the same
rule as used by Unix). The total number of spaces preceding the first non-blank character then
determines the line's indentation. Indentation cannot be split over multiple physical lines using
backslashes; the whitespace up to the first backslash determines the indentation.
Cross-platform compatibility note: because of the nature of text editors on non-UNIX platforms, it
is unwise to use a mixture of spaces and tabs for the indentation in a single source file.
A formfeed character may be present at the start of the line; it will be ignored for the indentation
calculations above. Formfeed characters occurring elsewhere in the leading whitespace have an
undefined effect (for instance, they may reset the space count to zero).
The indentation levels of consecutive lines are used to generate INDENT and DEDENT tokens, using
a stack, as follows.
Before the first line of the file is read, a single zero is pushed on the stack; this will never be popped
off again. The numbers pushed on the stack will always be strictly increasing from bottom to top. At
the beginning of each logical line, the line's indentation level is compared to the top of the stack. If it is
equal, nothing happens. If it is larger, it is pushed on the stack, and one INDENT token is generated. If
it is smaller, it must be one of the numbers occurring on the stack; all numbers on the stack that are
larger are popped off, and for each number popped off a DEDENT token is generated. At the end of
the file, a DEDENT token is generated for each number remaining on the stack that is larger than zero.
Here is an example of a correctly (though confusingly) indented piece of Python code:
def perm(l):
# Compute the list of all permutations of l
if len(l) <= 1:
return [l]
r = []
for i in range(len(l)):
s = l[:i] + l[i+1:]
p = perm(s)
for x in p:
r.append(l[i:i+1] + x)
return r
The following example shows various indentation errors:
http://davis.lbl.gov/Manuals/PYTHON/ref/indentation.html (1 of 2) [3/15/03 11:21:25 AM]
2.1.7 Indentation
def perm(l): # error: first line indented
for i in range(len(l)): # error: not indented
s = l[:i] + l[i+1:]
p = perm(l[:i] + l[i+1:]) # error: unexpected indent
for x in p:
r.append(l[i:i+1] + x)
return r # error: inconsistent dedent
(Actually, the first three errors are detected by the parser; only the last error is found by the lexical
analyzer -- the indentation of return r does not match a level popped off the stack.)
Python Reference Manual
Previous: 2.1.6 Blank lines Up: 2.1 Line structure Next: 2.1.8 Whitespace between tokens
Release 2.2.1, documentation updated on April 10, 2002.
See About this document... for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/ref/indentation.html (2 of 2) [3/15/03 11:21:25 AM]
2.1.8 Whitespace between tokens
Python Reference Manual
Previous: 2.1.7 Indentation Up: 2.1 Line structure Next: 2.2 Other tokens
2.1.8 Whitespace between tokens
Except at the beginning of a logical line or in string literals, the whitespace characters
space, tab and formfeed can be used interchangeably to separate tokens. Whitespace is
needed between two tokens only if their concatenation could otherwise be interpreted
as a different token (e.g., ab is one token, but a b is two tokens).
Python Reference Manual
Previous: 2.1.7 Indentation Up: 2.1 Line structure Next: 2.2 Other tokens
Release 2.2.1, documentation updated on April 10, 2002.
See About this document... for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/ref/whitespace.html [3/15/03 11:21:27 AM]
2.2 Other tokens
Python Reference Manual
Previous: 2.1.8 Whitespace between tokens Up: 2. Lexical analysis Next: 2.3
Identifiers and keywords
2.2 Other tokens
Besides NEWLINE, INDENT and DEDENT, the following categories of tokens exist:
identifiers, keywords, literals, operators, and delimiters. Whitespace characters (other
than line terminators, discussed earlier) are not tokens, but serve to delimit tokens.
Where ambiguity exists, a token comprises the longest possible string that forms a
legal token, when read from left to right.
Python Reference Manual
Previous: 2.1.8 Whitespace between tokens Up: 2. Lexical analysis Next: 2.3
Identifiers and keywords
Release 2.2.1, documentation updated on April 10, 2002.
See About this document... for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/ref/other-tokens.html [3/15/03 11:21:29 AM]
2.3 Identifiers and keywords
Python Reference Manual
Previous: 2.2 Other tokens Up: 2. Lexical analysis Next: 2.3.1 Keywords
2.3 Identifiers and keywords
Identifiers (also referred to as names) are described by the following lexical
definitions:
identifier ::= (letter|"_") (letter | digit | "_")*
letter ::= lowercase | uppercase
lowercase ::= "a"..."z"
uppercase ::= "A"..."Z"
digit ::= "0"..."9"
Download entire grammar as text.
Identifiers are unlimited in length. Case is significant.
Subsections
q 2.3.1 Keywords
q 2.3.2 Reserved classes of identifiers
Python Reference Manual
Previous: 2.2 Other tokens Up: 2. Lexical analysis Next: 2.3.1 Keywords
Release 2.2.1, documentation updated on April 10, 2002.
See About this document... for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/ref/identifiers.html [3/15/03 11:21:32 AM]
2.3.1 Keywords
Python Reference Manual
Previous: 2.3 Identifiers and keywords Up: 2.3 Identifiers and keywords Next: 2.3.2
Reserved classes of
2.3.1 Keywords
The following identifiers are used as reserved words, or keywords of the language, and
cannot be used as ordinary identifiers. They must be spelled exactly as written here:
and del for is raise
assert elif from lambda return
break else global not try
class except if or while
continue exec import pass yield
def finally in print
Python Reference Manual
Previous: 2.3 Identifiers and keywords Up: 2.3 Identifiers and keywords Next: 2.3.2
Reserved classes of
Release 2.2.1, documentation updated on April 10, 2002.
See About this document... for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/ref/keywords.html [3/15/03 11:21:34 AM]
2.3.2 Reserved classes of identifiers
Python Reference Manual
Previous: 2.3.1 Keywords Up: 2.3 Identifiers and keywords Next: 2.4 Literals
2.3.2 Reserved classes of identifiers
Certain classes of identifiers (besides keywords) have special meanings. These are:
Form Meaning Notes
_* Not imported by "from module import *" (1)
__*__ System-defined name
__* Class-private name mangling
(XXX need section references here.)
Note:
(1)
The special identifier "_" is used in the interactive interpreter to store the result
of the last evaluation; it is stored in the __builtin__ module. When not in
interactive mode, "_" has no special meaning and is not defined.
Python Reference Manual
Previous: 2.3.1 Keywords Up: 2.3 Identifiers and keywords Next: 2.4 Literals
Release 2.2.1, documentation updated on April 10, 2002.
See About this document... for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/ref/id-classes.html [3/15/03 11:21:36 AM]
2.4 Literals
Python Reference Manual
Previous: 2.3.2 Reserved classes of Up: 2. Lexical analysis Next: 2.4.1 String literals
2.4 Literals
Literals are notations for constant values of some built-in types.
Subsections
q 2.4.1 String literals
q 2.4.2 String literal concatenation
q 2.4.3 Numeric literals
q 2.4.4 Integer and long integer literals
q 2.4.5 Floating point literals
q 2.4.6 Imaginary literals
Python Reference Manual
Previous: 2.3.2 Reserved classes of Up: 2. Lexical analysis Next: 2.4.1 String literals
Release 2.2.1, documentation updated on April 10, 2002.
See About this document... for information on suggesting changes.
http://davis.lbl.gov/Manuals/PYTHON/ref/literals.html [3/15/03 11:21:38 AM]
2.4.1 String literals
Python Reference Manual
Previous: 2.4 Literals Up: 2.4 Literals Next: 2.4.2 String literal concatenation
2.4.1 String literals
String literals are described by the following lexical definitions:
stringliteral ::= [stringprefix](shortstring |
longstring)
stringprefix ::= "r" | "u" | "ur" | "R" | "U" | "UR" |
"Ur" | "uR"
shortstring ::= "'" shortstringitem* "'" | '"'
shortstringitem* '"'
longstring ::= "'''" longstringitem* "'''"
| '"""' longstringitem* '"""'
shortstringitem ::= shortstringchar | escapeseq
longstringitem ::= longstringchar | escapeseq
shortstringchar ::= <any ASCII character except "\" or
newline or the quote>
longstringchar ::= <any ASCII character except "\">
escapeseq ::= "\" <any ASCII character>
Download entire grammar as text.
One syntactic restriction not indicated by these productions is that whitespace is not
allowed between the stringprefix and the rest of the string literal.
In plain English: String literals can be enclosed in matching single quotes (') or
double quotes ("). They can also be enclosed in matching groups of three single or
double quotes (these are generally referred to as triple-quoted strings). The backslash
(\) character is used to escape characters that otherwise have a special meaning, such
as newline, backslash itself, or the quote character. String literals may optionally be
prefixed with a letter `r' or `R'; such strings are called raw strings and use different
rules for interpreting backslash escape sequences. A prefix of 'u' or 'U' makes the
string a Unicode string. Unicode strings use the Unicode character set as defined by
the Unicode Consortium and ISO 10646. Some additional escape sequences, described
http://davis.lbl.gov/Manuals/PYTHON/ref/strings.html (1 of 3) [3/15/03 11:21:41 AM]