The Python Standard Library » 5. Built-in Types 2. Built-in Functions


The Python Standard Library »


5. Built-in Types


5.1. Truth Value Testing
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:
    None
    False
    zero of any numeric type, for example, 0, 0L, 0.0, 0j.
    any empty sequence, for example, '', (), [].
    any empty mapping, for example, {}.
    instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False. [1]
All other values are considered true — so objects of many types are always true.
Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)



5.2. Boolean Operations — and, or, not

These are the Boolean operations, ordered by ascending priority:
Operation     Result     Notes
x or y     if x is false, then y, else x     (1)
x and y     if x is false, then x, else y     (2)
not x     if x is false, then True, else False     (3)

Notes:
    This is a short-circuit operator, so it only evaluates the second argument if the first one is False.
    This is a short-circuit operator, so it only evaluates the second argument if the first one is True.
    not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.




5.3. Comparisons

Comparison operations are supported by all objects.


This table summarizes the comparison operations:
Operation     Meaning     Notes
<     strictly less than     
<=     less than or equal     
>     strictly greater than     
>=     greater than or equal     
==     equal     
!=     not equal     (1)
is     object identity     
is not     negated object identity     

Notes:

    != can also be written <>, but this is an obsolete usage kept for backwards compatibility only. New code should always use !=.







###############################################################################################################################################
###############################################################################################################################################
###############################################################################################################################################
###############################################################################################################################################



###############################################################################################################################################
###############################################################################################################################################
###############################################################################################################################################
###############################################################################################################################################




###############################################################################################################################################
###############################################################################################################################################
###############################################################################################################################################
###############################################################################################################################################




###############################################################################################################################################
###############################################################################################################################################
###############################################################################################################################################
###############################################################################################################################################




###############################################################################################################################################
###############################################################################################################################################
###############################################################################################################################################
###############################################################################################################################################




###############################################################################################################################################
###############################################################################################################################################
###############################################################################################################################################
###############################################################################################################################################




###############################################################################################################################################
###############################################################################################################################################
###############################################################################################################################################
###############################################################################################################################################

5.4. Numeric Types — int, float, long, complex

Operation     Result     Notes
x + y     sum of x and y     
x - y     difference of x and y     
x * y     product of x and y     
x / y     quotient of x and y     (1)
x // y     (floored) quotient of x and y     (4)(5)
x % y     remainder of x / y     (4)
-x     x negated     
+x     x unchanged



    
abs(x)     absolute value or magnitude of x     (3)
int(x)     x converted to integer     (2)
long(x)     x converted to long integer     (2)
float(x)     x converted to floating point     (6)
complex(re,im)     a complex number with real part re, imaginary part im. im defaults to zero.     
c.conjugate()     conjugate of the complex number c. (Identity on real numbers)     
divmod(x, y)     the pair (x // y, x % y)     (3)(4)
pow(x, y)     x to the power y     (3)(7)
x ** y     x to the power y     (7)






5.4.1. Bit-string Operations on Integer Types

Plain and long integer types support additional operations that make sense only for bit-strings. Negative numbers are treated as their 2’s complement value (for long integers, this assumes a sufficiently large number of bits that no overflow occurs during the operation).

The priorities of the binary bitwise operations are all lower than the numeric operations and higher than the comparisons; the unary operation ~ has the same priority as the other unary numeric operations (+ and -).

This table lists the bit-string operations sorted in ascending priority:
Operation     Result     Notes
x | y     bitwise or of x and y     
x ^ y     bitwise exclusive or of x and y     
x & y     bitwise and of x and y     
x << n     x shifted left by n bits     (1)(2)
x >> n     x shifted right by n bits     (1)(3)
~x     the bits of x inverted     

Notes:

    Negative shift counts are illegal and cause a ValueError to be raised.
    A left shift by n bits is equivalent to multiplication by pow(2, n). A long integer is returned if the result exceeds the range of plain integers.
    A right shift by n bits is equivalent to division by pow(2, n).

5.4.2. Additional Methods on Float
float.as_integer_ratio()
float.hex()
float.fromhex(s)










5.5. Iterator Types
container.__iter__()
iterator.__iter__()
iterator.next()
5.5.1. Generator Types
Python’s generators provide a convenient way to implement the iterator protocol. If a container object’s __iter__() method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the __iter__() and next() methods. More information about generators can be found in the documentation for the yield expression.















5.6. Sequence Types — str, unicode, list, tuple, buffer, xrange

x in s     
x not in s
s + t
s * n, n * s
s[i]
s[i:j
s[i:j:k]


len(s)
min(s)
max(s)


5.6.1. String Methods

str.capitalize()
str.center(width[, fillchar])
str.count(sub[, start[, end]])
str.decode([encoding[, errors]])
str.encode([encoding[, errors]])
str.endswith(suffix[, start[, end]])
str.find(sub[, start[, end]])
str.format(*args, **kwargs)
str.index(sub[, start[, end]])
str.isalnum()
str.isalpha()
str.isdigit()
str.islower()
str.isspace()
str.istitle()
str.isupper()
str.join(iterable)
str.ljust(width[, fillchar])
str.lower()
str.lstrip([chars])
str.partition(sep)
str.replace(old, new[, count])
str.rfind(sub[, start[, end]])
str.rindex(sub[, start[, end]])
str.rjust(width[, fillchar])
str.rpartition(sep)
str.rsplit([sep[, maxsplit]])
str.rstrip([chars])
str.split([sep[, maxsplit]])
str.splitlines([keepends])
str.startswith(prefix[, start[, end]])
str.strip([chars])
str.swapcase()
str.title()
str.translate(table[, deletechars])
str.upper()
str.zfill(width)
unicode.isnumeric()
unicode.isdecimal()



5.6.2. String Formatting Operations

String and Unicode objects have one unique built-in operation: the % operator (modulo). This is also known as the string formatting or interpolation operator. Given format % values (where format is a string or Unicode object), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to the using sprintf() in the C language. If format is a Unicode object, or if any of the objects being converted using the %s conversion are Unicode objects, the result will also be a Unicode object.

If format requires a single argument, values may be a single non-tuple object. [4] Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary).

A conversion specifier contains two or more characters and has the following components, which must occur in this order:

    The '%' character, which marks the start of the specifier.
    Mapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)).
    Conversion flags (optional), which affect the result of some conversion types.
    Minimum field width (optional). If specified as an '*' (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.
    Precision (optional), given as a '.' (dot) followed by the precision. If specified as '*' (an asterisk), the actual width is read from the next element of the tuple in values, and the value to convert comes after the precision.
    Length modifier (optional).
    Conversion type.

When the right argument is a dictionary (or other mapping type), then the formats in the string must include a parenthesised mapping key into that dictionary inserted immediately after the '%' character. The mapping key selects the value to be formatted from the mapping. For example:

>>> print '%(language)s has %(#)03d quote types.' % \
...       {'language': "Python", "#": 2}
Python has 002 quote types.

In this case no * specifiers may occur in a format (since they require a sequential parameter list).

The conversion flag characters are:
Flag     Meaning
'#'     The value conversion will use the “alternate form” (where defined below).
'0'     The conversion will be zero padded for numeric values.
'-'     The converted value is left adjusted (overrides the '0' conversion if both are given).
' '     (a space) A blank should be left before a positive number (or empty string) produced by a signed conversion.
'+'     A sign character ('+' or '-') will precede the conversion (overrides a “space” flag).

A length modifier (h, l, or L) may be present, but is ignored as it is not necessary for Python – so e.g. %ld is identical to %d.

The conversion types are:
Conversion     Meaning     Notes
'd'     Signed integer decimal.     
'i'     Signed integer decimal.     
'o'     Signed octal value.     (1)
'u'     Obsolete type – it is identical to 'd'.     (7)
'x'     Signed hexadecimal (lowercase).     (2)
'X'     Signed hexadecimal (uppercase).     (2)
'e'     Floating point exponential format (lowercase).     (3)
'E'     Floating point exponential format (uppercase).     (3)
'f'     Floating point decimal format.     (3)
'F'     Floating point decimal format.     (3)
'g'     Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.     (4)
'G'     Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.     (4)
'c'     Single character (accepts integer or single character string).     
'r'     String (converts any Python object using repr()).     (5)
's'     String (converts any Python object using str()).     (6)
'%'     No argument is converted, results in a '%' character in the result.     

Notes:

    The alternate form causes a leading zero ('0') to be inserted between left-hand padding and the formatting of the number if the leading character of the result is not already a zero.

    The alternate form causes a leading '0x' or '0X' (depending on whether the 'x' or 'X' format was used) to be inserted between left-hand padding and the formatting of the number if the leading character of the result is not already a zero.

    The alternate form causes the result to always contain a decimal point, even if no digits follow it.

    The precision determines the number of digits after the decimal point and defaults to 6.

    The alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be.

    The precision determines the number of significant digits before and after the decimal point and defaults to 6.

    The %r conversion was added in Python 2.0.

    The precision determines the maximal number of characters used.

    If the object or format provided is a unicode string, the resulting string will also be unicode.

    The precision determines the maximal number of characters used.

    See PEP 237.

Since Python strings have an explicit length, %s conversions do not assume that '\0' is the end of the string.

For safety reasons, floating point precisions are clipped to 50; %f conversions for numbers whose absolute value is over 1e50 are replaced by %g conversions. [5] All other errors raise exceptions.

Additional string operations are defined in standard modules string and re.











5.6.3. XRange Type

5.6.4. Mutable Sequence Types

List objects support additional operations that allow in-place modification of the object.
Other mutable sequence types (when added to the language) should also support these operations.
Strings and tuples are immutable sequence types: such objects cannot be modified once created.

The following operations are defined on mutable sequence types (where x is an arbitrary object):
Operation     Result     Notes
s[i] = x     item i of s is replaced by x     
s[i:j] = t     slice of s from i to j is replaced by the contents of the iterable t     
del s[i:j]     same as s[i:j] = []     
s[i:j:k] = t     the elements of s[i:j:k] are replaced by those of t     (1)
del s[i:j:k]     removes the elements of s[i:j:k] from the list     
s.append(x)     same as s[len(s):len(s)] = [x]     (2)
s.extend(x)     same as s[len(s):len(s)] = x     (3)
s.count(x)     return number of i‘s for which s[i] == x     
s.index(x[, i[, j]])     return smallest k such that s[k] == x and i <= k < j     (4)
s.insert(i, x)     same as s[i:i] = [x]     (5)
s.pop([i])     same as x = s[i]; del s[i]; return x     (6)
s.remove(x)     same as del s[s.index(x)]     (4)
s.reverse()     reverses the items of s in place     (7)
s.sort([cmp[, key[, reverse]]])     sort the items of s in place     (7)(8)(9)(10)




5.7. Set Types — set, frozenset

class set([iterable])
class frozenset([iterable])

    Instances of set and frozenset provide the following operations:
    len(s)
    x in s
    x not in s
    isdisjoint(other)
    issubset(other)    set <= other
    set < other
    issuperset(other)   set >= other
    set > other
    union(other, ...)    set | other | ...
    intersection(other, ...)    set & other & ...
    difference(other, ...)    set - other - ...
    symmetric_difference(other)    set ^ other
    copy() of the second set (is a superset, but is not equal).



    The following table lists operations available for set that do not apply to immutable instances of frozenset:
    update(other, ...)    set |= other | ...
    intersection_update(other, ...)    set &= other & ...
    difference_update(other, ...)    set -= other | ...
    symmetric_difference_update(other)    set ^= other
    add(elem)
    remove(elem)
    discard(elem)
    pop()
    clear()






5.8. Mapping Types — dict
class dict([arg])
    These are the operations that dictionaries support (and therefore, custom mapping types should support too):
    len(d)
    d[key]
    d[key] = value
    del d[key]
    key in d
    key not in d
    iter(d)
    clear()
    copy()
    fromkeys(seq[, value])
    get(key[, default])
    has_key(key)
    items()
    iteritems()
    iterkeys()
    itervalues()
    keys()
    pop(key[, default])
    popitem()
    setdefault(key[, default])
    update([other])
    values()






5.9. File Objects
Files have the following methods:
file.close()
file.flush()
file.fileno()
file.isatty()
file.next()
file.read([size])
file.readline([size])
file.readlines([sizehint])
file.xreadlines()
file.seek(offset[, whence])
file.tell()
file.write(str)
file.writelines(sequence)
file.closed
file.encoding
file.errors
file.mode
file.name
file.newlines
file.softspace





5.10. Context Manager Types
contextmanager.__enter__()
contextmanager.__exit__(exc_type, exc_val, exc_tb)









5.11. Other Built-in Types
The interpreter supports several other kinds of objects. Most of these support only one or two operations.

5.11.1. Modules                          : module
5.11.2. Classes and Class Instances      : classobj        instance
5.11.3. Functions                        : function
5.11.4. Methods                          : instancemethode
5.11.5. Code Objects
5.11.6. Type Objects                     : type
5.11.7. The Null Object                  : NoneType
5.11.8. The Ellipsis Object
5.11.9. Boolean Values                   : bool
5.11.10. Internal Objects
See The standard type hierarchy for this information. It describes :
                                            stack frame objects,
                                            traceback objects,
                                            slice objects.









5.12. Special Attributes
object.__dict__
object.__methods__
object.__members__
instance.__class__
class.__bases__
class.__name__

The following attributes are only supported by new-style classes.
class.__mro__
class.mro()
class.__subclasses__()







+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++



+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++




+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++




+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++




+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++




+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++




+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++











2. Built-in Functions
The Python interpreter has a number of functions built into it that are always available. They are listed here in alphabetical order.

all(iterable)
any(iterable)
basestring()
bin(x)
bool([x])
callable(object)
chr(i)
classmethod(function)
cmp(x, y)
complex([real[, imag]])
delattr(object, name)
dict([arg])
dir([object])
divmod(a, b)


enumerate(sequence[, start=0])
eval(expression[, globals[, locals]])
file(filename[, mode[, bufsize]])
filter(function, iterable)
float([x])
format(value[, format_spec])
frozenset([iterable])
getattr(object, name[, default])
globals()




hasattr(object, name)
help([object])
hex(x)
id(object)
input([prompt])
int([x[, base]])
isinstance(object, classinfo)
issubclass(class, classinfo)
iter(o[, sentinel])



len(s)
list([iterable])
locals()
long([x[, base]])
map(function, iterable, ...)
max(iterable[, args...][, key])
max(a,b,c,key=func)).
min(iterable[, args...][, key])
min(a,b,c,key=func)).
next(iterator[, default])


object()
oct(x)
open(filename[, mode[, bufsize]])
ord(c)
pow(x, y[, z])
print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout])
property([fget[, fset[, fdel[, doc]]]])


range([start], stop[, step])
raw_input([prompt])
reload(module)
repr(object)
reversed(seq)
round(x[, n])
set([iterable])
setattr(object, name, value)
slice([start], stop[, step])
sorted(iterable[, cmp[, key[, reverse]]])
staticmethod(function)
str([object])
sum(iterable[, start])
super(type[, object-or-type])
tuple([iterable])
type(object)
type(name, bases, dict)


unichr(i)
unicode([object[, encoding[, errors]]])
vars([object])
xrange([start], stop[, step])
zip([iterable, ...])
__import__(name[, globals[, locals[, fromlist[, level]]]])



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值