12
|
Python Pocket Reference
0177, 0x9ff
Octal and hex integer constants
3+4j, 3.0+4.0j, 3J
Complex numbers
Operations
Number types support all number operations (see Table 6,
earlier in this book). In mixed-type expressions, Python con-
verts operands up to the type of the “highest” type, where
integer is lower than long, which is lower than floating-point,
which is lower than complex.
In Version 2.2 and later, integer results are automatically
promoted to longs instead of overflowing, so there is no need
to manually code an integer with a trailing letter “L” to force
long precision. Also, in Version 2.2 and later, there are two
flavors of division (
/ and //).
Strings
Strings are immutable (i.e., unchangeable) arrays of charac-
ters, accessed by offset.
Literals
Strings are written as a series of characters in quotes.
"Python's", 'Python"s'
Double and single quotes work the same, and each can
embed unescaped quotes of the other kind.
"""This is a
multiline block"""
Triple-quoted blocks collect lines into a single string,
with end-of-line markers (
\n) inserted between the origi-
nal lines.
Specific Built-in Types
|
13
'Python\'s\n'
Backslash escape code sequences (see Table 7) are
replaced with the special-character byte values they rep-
resent (e.g.,
'\n' is a byte with binary value 012).
"This" "is" "concatenated"
Adjacent string constants are concatenated.
r'a raw\string', R'another\one'
Raw strings: backslashes are retained literally (except at
the end of a string). This is handy for regular expressions
and DOS directory paths; e.g.,
r'c:\dir1\file'.
u"..."
Unicode string constants (see the section “Unicode
Strings,” later in this book).
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
hex
a
a
\Uhhhhhhhh takes exactly eight hexadecimal digits (h); both \u and \U can be used only in Uni-
code string constants.
\b Backspace \xhh Hex digits value
\f Formfeed \ooo Octal digits value
\n Linefeed \0 Null (not end of
string)
\r Carriage return \other Not an escape
14
|
Python Pocket Reference
Operations
String operations comprise all sequence operations (shown
earlier in Table 3), plus
% string formatting expressions, tem-
plate substitution, and string method calls. Also see the
re
string pattern-matching module in the section “The re Pattern-
Matching Module,” and string-related built-in funct
ions in the
section “Built-In Functions,” both later in this book.
String formatting
String formatting replaces % 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. If keynames are used on the left,
a dictionary must be supplied on the right.
'The knights who say %s!' % 'Ni'
Result: "The knights who say Ni!"
"%d %s %d you" % (1, 'spam', 4.0)
Result: "1 spam 4 you"
"%(n)d %(x)s" % {"n":1, "x":"spam"}
Result: "1 spam"
%[(name)][flags][width][.precision]code
General target format
flags can be - (left-justify), + (numeric sign), a space (leave a
blank before positive numbers), and
0 (zero fill); width is the
total field width;
precision gives digits after .; and code is a
character from Table 8. Both
width and precision 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 converts any object to its
print representation string.
Specific Built-in Types
|
15
Template string substitution
In Python 2.4, a form of simple string substitution is pro-
vided as an alternative to the string formatting described in
the prior section. The usual way of substituting variables is
with the
% operator:
>>> '%(page)i: %(title)s' % {'page':2, 'title': 'The Best
of Times'}
'2: The Best of Times'
For simpler formatting tasks, a Template class has been added
to the
string module that uses $ to indicate a substitution:
>>> import string
>>> t = string.Template('$page: $title')
>>> t.substitute({'page':2, 'title': 'The Best of Times'})
'2: The Best of Times'
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'
Table 8. % string formatting codes
Code Meaning Code Meaning
s String (or any object, uses str()) Xx with uppercase
rs, but uses repr(), not str() e Floating-point exponent
c Character Ee with uppercase
d Decimal (integer) f Floating-point decimal
i Integer Ff with uppercase
u Unsigned (integer) g Floating-point e or f
o
Octal integer G Floating-point E or F
x
Hex integer % Literal ‘%’

Get Python Pocket Reference, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.