📄 appendix_a.txt
字号:
or string may be explicitly converted to a float using the
`float()` function.
SEE ALSO, [float]
complex
An object containing two floats, representing real and
imaginary components of a number. A numeric expression
that involves both int/long/float types and complex types
promotes all component types to complex before performing
the computation. There is no way to spell a literal
complex in Python, but an addition such as '1.1+2j' is the
usual way of computing a complex value. A 'j' or 'J'
following a float or int literal indicates an imaginary
number. An int, long, or string may be explicitly
converted to a complex using the `complex()` function. If
two float/int arguments are passed to `complex()`, the
second is the imaginary component of the constructed
number (e.g., 'complex(1.1,2)').
string
An immutable sequence of 8-bit character values. Unlike in
many programming languages, there is no "character" type
in Python, merely strings that happen to have length one.
String objects have a variety of methods to modify strings,
but such methods always return a new string object rather
than modify the initial object itself. The built-in
`chr()` function will return a length-one string whose
ordinal value is the passed integer. The `str()` function
will return a string representation of a passed in object.
For example:
>>> ord('a')
97
>>> chr(97)
'a'
>>> str(97)
'97'
SEE ALSO, [string]
unicode
An immutable sequence of Unicode characters. There is no
datatype for a single Unicode character, but unicode
strings of length-one contain a single character. Unicode
strings contain a similar collection of methods to string
objects, and like the latter, unicode methods return new
unicode objects rather than modify the initial object. See
Chapter 2 and Appendix C for additional discussion, of
Unicode.
TOPIC -- String Interpolation
--------------------------------------------------------------------
Literal strings and unicode strings may contain embedded format
codes. When a string contains format codes, values may be
-interpolated- into the string using the '%' operator and a
tuple or dictionary giving the values to substitute in.
Strings that contain format codes may follow either of two
patterns. The simpler pattern uses format codes with the syntax
'%[flags][len[.precision]]<type>'. Interpolating a string with
format codes on this pattern requires '%' combination with a
tuple of matching length and content datatypes. If only one
value is being interpolated, you may give the bare item rather
than a tuple of length one. For example:
>>> "float %3.1f, int %+d, hex %06x" % (1.234, 1234, 1234)
'float 1.2, int +1234, hex 0004d2'
>>> '%e' % 1234
'1.234000e+03'
>>> '%e' % (1234,)
'1.234000e+03'
The (slightly) more complex pattern for format codes embeds a
name within the format code, which is then used as a string key
to an interpolation dictionary. The syntax of this pattern is
'%(key)[flags][len[.precision]]<type>'. Interpolating a string
with this style of format codes requires '%' combination with a
dictionary that contains all the named keys, and whose
corresponding values contain acceptable datatypes. For example:
>>> dct = {'ratio':1.234, 'count':1234, 'offset':1234}
>>> "float %(ratio)3.1f, int %(count)+d, hex %(offset)06x" % dct
'float 1.2, int +1234, hex 0004d2'
You -may not- mix tuple interpolation and dictionary
interpolation within the same string.
I mentioned that datatypes must match format codes. Different
format codes accept a different range of datatypes, but the
rules are almost always what you would expect. Generally,
numeric data will be promoted or demoted as necessary, but
strings and complex types cannot be used for numbers.
One useful style of using dictionary interpolation is against
the global and/or local namespace dictionary. Regular
bound names defined in scope can be interpolated into strings.
>>> s = "float %(ratio)3.1f, int %(count)+d, hex %(offset)06x"
>>> ratio = 1.234
>>> count = 1234
>>> offset = 1234
>>> s % globals()
'float 1.2, int +1234, hex 0004d2'
If you want to look for names across scope, you can create an
ad hoc dictionary with both local and global names:
>>> vardct = {}
>>> vardct.update(globals())
>>> vardct.update(locals())
>>> interpolated = somestring % vardct
The flags for format codes consist of the following:
#*--------------- Format code flags ----------------------#
0 Pad to length with leading zeros
- Align the value to the left within its length
_ (space) Pad to length with leading spaces
+ Explicitly indicate the sign of positive values
When a length is included, it specifies the -minimum- length of
the interpolated formatting. Numbers that will not fit within
a length simply occupy more bytes than specified. When a
precision is included, the length of those digits to the right
of the decimal are included in the total length:
>>> '[%f]' % 1.234
'[1.234000]'
>>> '[%5f]' % 1.234
'[1.234000]'
>>> '[%.1f]' % 1.234
'[1.2]'
>>> '[%5.1f]' % 1.234
'[ 1.2]'
>>> '[%05.1f]' % 1.234
'[001.2]'
The formatting types consist of the following:
#*-------------- Format type codes -----------------------#
d Signed integer decimal
i Signed integer decimal
o Unsigned octal
u Unsigned decimal
x Lowercase unsigned hexadecimal
X Uppercase unsigned hexadecimal
e Lowercase exponential format floating point
E Uppercase exponential format floating point
f Floating point decimal format
g Floating point: exponential format if -4 < exp < precision
G Uppercase version of 'g'
c Single character: integer for chr(i) or length-one string
r Converts any Python object using repr()
s Converts any Python object using str()
% The '%' character, e.g.: '%%%d' % (1) --> '%1'
One more special format code style allows the use of a '*' in
place of a length. In this case, the interpolated tuple must
contain an extra element for the formatted length of each
format code, preceding the value to format. For example:
>>> "%0*d # %0*.2f" % (4, 123, 4, 1.23)
'0123 # 1.23'
>>> "%0*d # %0*.2f" % (6, 123, 6, 1.23)
'000123 # 001.23'
TOPIC -- Printing
--------------------------------------------------------------------
The least-sophisticated form of textual output in Python is
writing to open files. In particular, the STDOUT and STDERR
streams can be accessed using the pseudo-files `sys.stdout` and
`sys.stderr`. Writing to these is just like writing to any
other file; for example:
>>> import sys
>>> try:
... # some fragile action
... sys.stdout.write('result of action\n')
... except:
... sys.stderr.write('could not complete action\n')
...
result of action
You cannot seek within STDOUT or STDERR--generally you should
consider these as pure sequential outputs.
Writing to STDOUT and STDERR is fairly inflexible, and most of
the time the 'print' statement accomplishes the same purpose
more flexibly. In particular, methods like `sys.stdout.write()`
only accept a single string as an argument, while 'print' can
handle any number of arguments of any type. Each argument is
coerced to a string using the equivalent of 'repr(obj)'. For
example:
>>> print "Pi: %.3f" % 3.1415, 27+11, {3:4,1:2}, (1,2,3)
Pi: 3.142 38 {1: 2, 3: 4} (1, 2, 3)
Each argument to the 'print' statment is evaluated before it is
printed, just as when an argument is passed to a function. As a
consequence, the canonical representation of an object is
printed, rather than the exact form passed as an argument. In my
example, the dictionary prints in a different order than it was
defined in, and the spacing of the list and dictionary is
slightly different. String interpolation is also peformed and is
a very common means of defining an output format precisely.
There are a few things to watch for with the 'print' statement.
A space is printed between each argument to the statement. If
you want to print several objects without a separating space,
you will need to use string concatenation or string
interpolation to get the right result. For example:
>>> numerator, denominator = 3, 7
>>> print repr(numerator)+"/"+repr(denominator)
3/7
>>> print "%d/%d" % (numerator, denominator)
3/7
By default, a 'print' statement adds a linefeed to the end of
its output. You may eliminate the linefeed by adding a
trailing comma to the statement, but you still wind up with a
space added to the end:
>>> letlist = ('a','B','Z','r','w')
>>> for c in letlist: print c, # inserts spaces
...
a B Z r w
Assuming these spaces are unwanted, you must either use
`sys.stdout.write()` or otherwise calculate the space-free
string you want:
>>> for c in letlist+('\n',): # no spaces
... sys.stdout.write(c)
...
aBZrw
>>> print ''.join(letlist)
aBZrw
There is a special form of the 'print' statement that redirects
its output somewhere other than STDOUT. The 'print' statement
itself can be followed by two greater-than signs, then a
writable file-like object, then a comma, then the remainder of
the (printed) arguments. For example:
>>> print >> open('test','w'), "Pi: %.3f" % 3.1415, 27+11
>>> open('test').read()
'Pi: 3.142 38\n'
Some Python programmers (including your author) consider this
special form overly "noisy," but it -is- occassionally useful
for quick configuration of output destinations.
If you want a function that would do the same thing as a
'print' statement, the following one does so, but without any
facility to eliminate the trailing linefeed or redirect output:
#*--------- Functional version of print statement --------#
def print_func(*args):
import sys
sys.stdout.write(' '.join(map(repr,args))+'\n')
Readers could enhance this to add the missing capabilities, but
using 'print' as a statement is the clearest approach,
generally.
SEE ALSO, `sys.stderr`, `sys.stdout`
TOPIC -- Container Types
--------------------------------------------------------------------
tuple
An immutable sequence of (heterogeneous) objects. Being
immutable, the membership and length of a tuple cannot be
modified after creation. However, tuple elements and
subsequences can be accessed by subscripting and slicing,
and new tuples can be constructed from such elements and
slices. Tuples are similar to "records" in some other
programming languages.
The constructor syntax for a tuple is commas between listed
items; in many contexts, parentheses around a constructed
list are required to disambiguate a tuple for other
constructs such as function arguments, but it is the commas
not the parentheses that construct a tuple. Some examples:
>>> tup = 'spam','eggs','bacon','sausage'
>>> newtup = tup[1:3] + (1,2,3) + (tup[3],)
>>> newtup
('eggs', 'bacon', 1, 2, 3, 'sausage')
The function `tuple()` may also be used to construct a
tuple from another sequence type (either a list or custom
sequence type).
SEE ALSO, [tuple]
list
A mutable sequence of objects. Like a tuple, list elements
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -