Built-in Functions¶
The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.
Built-in Functions |
|||
---|---|---|---|
- abs(number, /)¶
Return the absolute value of a number. The argument may be an integer, a floating-point number, or an object implementing
__abs__()
. If the argument is a complex number, its magnitude is returned.
- aiter(async_iterable, /)¶
Return an asynchronous iterator for an asynchronous iterable. Equivalent to calling
x.__aiter__()
.Note: Unlike
iter()
,aiter()
has no 2-argument variant.Added in version 3.10.
- all(iterable, /)¶
Return
True
if all elements of the iterable are true (or if the iterable is empty). Equivalent to:def all(iterable): for element in iterable: if not element: return False return True
- awaitable anext(async_iterator, /)¶
- awaitable anext(async_iterator, default, /)
When awaited, return the next item from the given asynchronous iterator, or default if given and the iterator is exhausted.
This is the async variant of the
next()
builtin, and behaves similarly.This calls the
__anext__()
method of async_iterator, returning an awaitable. Awaiting this returns the next value of the iterator. If default is given, it is returned if the iterator is exhausted, otherwiseStopAsyncIteration
is raised.Added in version 3.10.
- any(iterable, /)¶
Return
True
if any element of the iterable is true. If the iterable is empty, returnFalse
. Equivalent to:def any(iterable): for element in iterable: if element: return True return False
- ascii(object, /)¶
As
repr()
, return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned byrepr()
using\x
,\u
, or\U
escapes. This generates a string similar to that returned byrepr()
in Python 2.
- bin(integer, /)¶
Convert an integer number to a binary string prefixed with “0b”. The result is a valid Python expression. If integer is not a Python
int
object, it has to define an__index__()
method that returns an integer. Some examples:>>> bin(3) '0b11' >>> bin(-10) '-0b1010'
If the prefix “0b” is desired or not, you can use either of the following ways.
>>> format(14, '#b'), format(14, 'b') ('0b1110', '1110') >>> f'{14:#b}', f'{14:b}' ('0b1110', '1110')
See also
format()
for more information.
- class bool(object=False, /)¶
Return a Boolean value, i.e. one of
True
orFalse
. The argument is converted using the standard truth testing procedure. If the argument is false or omitted, this returnsFalse
; otherwise, it returnsTrue
. Thebool
class is a subclass ofint
(see Numeric Types — int, float, complex). It cannot be subclassed further. Its only instances areFalse
andTrue
(see Boolean Type - bool).Changed in version 3.7: The parameter is now positional-only.
- breakpoint(*args, **kws)¶
This function drops you into the debugger at the call site. Specifically, it calls
sys.breakpointhook()
, passingargs
andkws
straight through. By default,sys.breakpointhook()
callspdb.set_trace()
expecting no arguments. In this case, it is purely a convenience function so you don’t have to explicitly importpdb
or type as much code to enter the debugger. However,sys.breakpointhook()
can be set to some other function andbreakpoint()
will automatically call that, allowing you to drop into the debugger of choice. Ifsys.breakpointhook()
is not accessible, this function will raiseRuntimeError
.By default, the behavior of
breakpoint()
can be changed with thePYTHONBREAKPOINT
environment variable. Seesys.breakpointhook()
for usage details.Note that this is not guaranteed if
sys.breakpointhook()
has been replaced.Raises an auditing event
builtins.breakpoint
with argumentbreakpointhook
.Added in version 3.7.
- class bytearray(source=b'')
- class bytearray(source, encoding, errors='strict')
Return a new array of bytes. The
bytearray
class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that thebytes
type has, see Bytes and Bytearray Operations.The optional source parameter can be used to initialize the array in a few different ways:
If it is a string, you must also give the encoding (and optionally, errors) parameters;
bytearray()
then converts the string to bytes usingstr.encode()
.If it is an integer, the array will have that size and will be initialized with null bytes.
If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
If it is an iterable, it must be an iterable of integers in the range
0 <= x < 256
, which are used as the initial contents of the array.
Without an argument, an array of size 0 is created.
See also Binary Sequence Types — bytes, bytearray, memoryview and Bytearray Objects.
- class bytes(source=b'')
- class bytes(source, encoding, errors='strict')
Return a new “bytes” object which is an immutable sequence of integers in the range
0 <= x < 256
.bytes
is an immutable version ofbytearray
– it has the same non-mutating methods and the same indexing and slicing behavior.Accordingly, constructor arguments are interpreted as for
bytearray()
.Bytes objects can also be created with literals, see String and Bytes literals.
See also Binary Sequence Types — bytes, bytearray, memoryview, Bytes Objects, and Bytes and Bytearray Operations.
- callable(object, /)¶
Return
True
if the object argument appears callable,False
if not. If this returnsTrue
, it is still possible that a call fails, but if it isFalse
, calling object will never succeed. Note that classes are callable (calling a class returns a new instance); instances are callable if their class has a__call__()
method.Added in version 3.2: This function was first removed in Python 3.0 and then brought back in Python 3.2.
- chr(codepoint, /)¶
Return the string representing a character with the specified Unicode code point. For example,
chr(97)
returns the string'a'
, whilechr(8364)
returns the string'€'
. This is the inverse oford()
.The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16).
ValueError
will be raised if it is outside that range.
- @classmethod¶
Transform a method into a class method.
A class method receives the class as an implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:
class C: @classmethod def f(cls, arg1, arg2): ...
The
@classmethod
form is a function decorator – see Function definitions for details.A class method can be called either on the class (such as
C.f()
) or on an instance (such asC().f()
). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.Class methods are different than C++ or Java static methods. If you want those, see
staticmethod()
in this section. For more information on class methods, see The standard type hierarchy.Changed in version 3.9: Class methods can now wrap other descriptors such as
property()
.Changed in version 3.10: Class methods now inherit the method attributes (
__module__
,__name__
,__qualname__
,__doc__
and__annotations__
) and have a new__wrapped__
attribute.Deprecated since version 3.11, removed in version 3.13: Class methods can no longer wrap other descriptors such as
property()
.
- compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)¶
Compile the source into a code or AST object. Code objects can be executed by
exec()
oreval()
. source can either be a normal string, a byte string, or an AST object. Refer to theast
module documentation for information on how to work with AST objects.The filename argument should give the file from which the code was read; pass some recognizable value if it wasn’t read from a file (
'<string>'
is commonly used).The mode argument specifies what kind of code must be compiled; it can be
'exec'
if source consists of a sequence of statements,'eval'
if it consists of a single expression, or'single'
if it consists of a single interactive statement (in the latter case, expression statements that evaluate to something other thanNone
will be printed).The optional arguments flags and dont_inherit control which compiler options should be activated and which future features should be allowed. If neither is present (or both are zero) the code is compiled with the same flags that affect the code that is calling
compile()
. If the flags argument is given and dont_inherit is not (or is zero) then the compiler options and the future statements specified by the flags argument are used in addition to those that would be used anyway. If dont_inherit is a non-zero integer then the flags argument is it – the flags (future features and compiler options) in the surrounding code are ignored.Compiler options and future statements are specified by bits which can be bitwise ORed together to specify multiple options. The bitfield required to specify a given future feature can be found as the
compiler_flag
attribute on the_Feature
instance in the__future__
module. Compiler flags can be found inast
module, withPyCF_
prefix.The argument optimize specifies the optimization level of the compiler; the default value of
-1
selects the optimization level of the interpreter as given by-O
options. Explicit levels are0
(no optimization;__debug__
is true),1
(asserts are removed,__debug__
is false) or2
(docstrings are removed too).This function raises
SyntaxError
if the compiled source is invalid, andValueError
if the source contains null bytes.If you want to parse Python code into its AST representation, see
ast.parse()
.Raises an auditing event
compile
with argumentssource
andfilename
. This event may also be raised by implicit compilation.Note
When compiling a string with multi-line code in
'single'
or'eval'
mode, input must be terminated by at least one newline character. This is to facilitate detection of incomplete and complete statements in thecode
module.Warning
It is possible to crash the Python interpreter with a sufficiently large/complex string when compiling to an AST object due to stack depth limitations in Python’s AST compiler.
Changed in version 3.2: Allowed use of Windows and Mac newlines. Also, input in
'exec'
mode does not have to end in a newline anymore. Added the optimize parameter.Changed in version 3.5: Previously,
TypeError
was raised when null bytes were encountered in source.Added in version 3.8:
ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
can now be passed in flags to enable support for top-levelawait
,async for
, andasync with
.
- class complex(number=0, /)¶
- class complex(string, /)
- class complex(real=0, imag=0)
Convert a single string or number to a complex number, or create a complex number from real and imaginary parts.
Examples:
>>> complex('+1.23') (1.23+0j) >>> complex('-4.5j') -4.5j >>> complex('-1.23+4.5j') (-1.23+4.5j) >>> complex('\t( -1.23+4.5J )\n') (-1.23+4.5j) >>> complex('-Infinity+NaNj') (-inf+nanj) >>> complex(1.23) (1.23+0j) >>> complex(imag=-4.5) -4.5j >>> complex(-1.23, 4.5) (-1.23+4.5j)
If the argument is a string, it must contain either a real part (in the same format as for
float()
) or an imaginary part (in the same format but with a'j'
or'J'
suffix), or both real and imaginary parts (the sign of the imaginary part is mandatory in this case). The string can optionally be surrounded by whitespaces and the round parentheses'('
and')'
, which are ignored. The string must not contain whitespace between'+'
,'-'
, the'j'
or'J'
suffix, and the decimal number. For example,complex('1+2j')
is fine, butcomplex('1 + 2j')
raisesValueError
. More precisely, the input must conform to thecomplexvalue
production rule in the following grammar, after parentheses and leading and trailing whitespace characters are removed:complexvalue ::=
floatvalue
|floatvalue
("j" | "J") |floatvalue
sign
absfloatvalue
("j" | "J")If the argument is a number, the constructor serves as a numeric conversion like
int
andfloat
. For a general Python objectx
,complex(x)
delegates tox.__complex__()
. If__complex__()
is not defined then it falls back to__float__()
. If__float__()
is not defined then it falls back to__index__()
.If two arguments are provided or keyword arguments are used, each argument may be any numeric type (including complex). If both arguments are real numbers, return a complex number with the real component real and the imaginary component imag. If both arguments are complex numbers, return a complex number with the real component
real.real-imag.imag
and the imaginary componentreal.imag+imag.real
. If one of arguments is a real number, only its real component is used in the above expressions.If all arguments are omitted, returns
0j
.The complex type is described in Numeric Types — int, float, complex.
Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.
Changed in version 3.8: Falls back to
__index__()
if__complex__()
and__float__()
are not defined.
- delattr(object, name, /)¶
This is a relative of
setattr()
. The arguments are an object and a string. The string must be the name of one of the object’s attributes. The function deletes the named attribute, provided the object allows it. For example,delattr(x, 'foobar')
is equivalent todel x.foobar
. name need not be a Python identifier (seesetattr()
).
- class dict(**kwargs)
- class dict(mapping, /, **kwargs)
- class dict(iterable, /, **kwargs)
Create a new dictionary. The
dict
object is the dictionary class. Seedict
and Mapping Types — dict for documentation about this class.For other containers see the built-in
list
,set
, andtuple
classes, as well as thecollections
module.
- dir()¶
- dir(object, /)
Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.
If the object has a method named
__dir__()
, this method will be called and must return the list of attributes. This allows objects that implement a custom__getattr__()
or__getattribute__()
function to customize the waydir()
reports their attributes.If the object does not provide
__dir__()
, the function tries its best to gather information from the object’s__dict__
attribute, if defined, and from its type object. The resulting list is not necessarily complete and may be inaccurate when the object has a custom__getattr__()
.The default
dir()
mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:If the object is a module object, the list contains the names of the module’s attributes.
If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.
The resulting list is sorted alphabetically. For example:
>>> import struct >>> dir() # show the names in the module namespace ['__builtins__', '__name__', 'struct'] >>> dir(struct) # show the names in the struct module ['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__initializing__', '__loader__', '__name__', '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', 'unpack', 'unpack_from'] >>> class Shape: ... def __dir__(self): ... return ['area', 'perimeter', 'location'] ... >>> s = Shape() >>> dir(s) ['area', 'location', 'perimeter']
Note
Because
dir()
is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.
- divmod(a, b, /)¶
Take two (non-complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as
(a // b, a % b)
. For floating-point numbers the result is(q, a % b)
, where q is usuallymath.floor(a / b)
but may be 1 less than that. In any caseq * b + a % b
is very close to a, ifa % b
is non-zero it has the same sign as b, and0 <= abs(a % b) < abs(b)
.
- enumerate(iterable, start=0)¶
Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The
__next__()
method of the iterator returned byenumerate()
returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
Equivalent to:
def enumerate(iterable, start=0): n = start for elem in iterable: yield n, elem n += 1
- eval(source, /, globals=None, locals=None)¶
- Parameters:
source (
str
| code object) – A Python expression.globals (
dict
|None
) – The global namespace (default:None
).locals (mapping |
None
) – The local namespace (default:None
).
- Returns:
The result of the evaluated expression.
- Raises:
Syntax errors are reported as exceptions.
Warning
This function executes arbitrary code. Calling it with user-supplied input may lead to security vulnerabilities.
The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals mappings as global and local namespace. If the globals dictionary is present and does not contain a value for the key
__builtins__
, a reference to the dictionary of the built-in modulebuiltins
is inserted under that key before expression is parsed. That way you can control what builtins are available to the executed code by inserting your own__builtins__
dictionary into globals before passing it toeval()
. If the locals mapping is omitted it defaults to the globals dictionary. If both mappings are omitted, the expression is executed with the globals and locals in the environment whereeval()
is called. Note, eval() will only have access to the nested scopes (non-locals) in the enclosing environment if they are already referenced in the scope that is callingeval()
(e.g. via anonlocal
statement).Example:
>>> x = 1 >>> eval('x+1') 2
This function can also be used to execute arbitrary code objects (such as those created by
compile()
). In this case, pass a code object instead of a string. If the code object has been compiled with'exec'
as the mode argument,eval()
's return value will beNone
.Hints: dynamic execution of statements is supported by the
exec()
function. Theglobals()
andlocals()
functions return the current global and local dictionary, respectively, which may be useful to pass around for use byeval()
orexec()
.If the given source is a string, then leading and trailing spaces and tabs are stripped.
See
ast.literal_eval()
for a function that can safely evaluate strings with expressions containing only literals.Raises an auditing event
exec
with the code object as the argument. Code compilation events may also be raised.Changed in version 3.13: The globals and locals arguments can now be passed as keywords.
Changed in version 3.13: The semantics of the default locals namespace have been adjusted as described for the
locals()
builtin.
- exec(source, /, globals=None, locals=None, *, closure=None)¶
Warning
This function executes arbitrary code. Calling it with user-supplied input may lead to security vulnerabilities.
This function supports dynamic execution of Python code. source must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [1] If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section File input in the Reference Manual). Be aware that the
nonlocal
,yield
, andreturn
statements may not be used outside of function definitions even within the context of code passed to theexec()
function. The return value isNone
.In all cases, if the optional parts are omitted, the code is executed in the current scope. If only globals is provided, it must be a dictionary (and not a subclass of dictionary), which will be used for both the global and the local variables. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at the module level, globals and locals are the same dictionary.
Note
When
exec
gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition. This means functions and classes defined in the executed code will not be able to access variables assigned at the top level (as the “top level” variables are treated as class variables in a class definition).If the globals dictionary does not contain a value for the key
__builtins__
, a reference to the dictionary of the built-in modulebuiltins
is inserted under that key. That way you can control what builtins are available to the executed code by inserting your own__builtins__
dictionary into globals before passing it toexec()
.The closure argument specifies a closure–a tuple of cellvars. It’s only valid when the object is a code object containing free (closure) variables. The length of the tuple must exactly match the length of the code object’s
co_freevars
attribute.Raises an auditing event
exec
with the code object as the argument. Code compilation events may also be raised.Note
The built-in functions
globals()
andlocals()
return the current global and local namespace, respectively, which may be useful to pass around for use as the second and third argument toexec()
.Note
The default locals act as described for function
locals()
below. Pass an explicit locals dictionary if you need to see effects of the code on locals after functionexec()
returns.Changed in version 3.11: Added the closure parameter.
Changed in version 3.13: The globals and locals arguments can now be passed as keywords.
Changed in version 3.13: The semantics of the default locals namespace have been adjusted as described for the
locals()
builtin.
- filter(function, iterable, /)¶
Construct an iterator from those elements of iterable for which function is true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is
None
, the identity function is assumed, that is, all elements of iterable that are false are removed.Note that
filter(function, iterable)
is equivalent to the generator expression(item for item in iterable if function(item))
if function is notNone
and(item for item in iterable if item)
if function isNone
.See
itertools.filterfalse()
for the complementary function that returns elements of iterable for which function is false.
- class float(number=0.0, /)¶
- class float(string, /)
Return a floating-point number constructed from a number or a string.
Examples:
>>> float('+1.23') 1.23 >>> float(' -12345\n') -12345.0 >>> float('1e-003') 0.001 >>> float('+1E6') 1000000.0 >>> float('-Infinity') -inf
If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be
'+'
or'-'
; a'+'
sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or positive or negative infinity. More precisely, the input must conform to thefloatvalue
production rule in the following grammar, after leading and trailing whitespace characters are removed:sign ::= "+" | "-" infinity ::= "Infinity" | "inf" nan ::= "nan" digit ::= <a Unicode decimal digit, i.e. characters in Unicode general category Nd> digitpart ::=
digit
(["_"]digit
)* number ::= [digitpart
] "."digitpart
|digitpart
["."] exponent ::= ("e" | "E") [sign
]digitpart
floatnumber ::=number
[exponent
] absfloatvalue ::=floatnumber
|infinity
|nan
floatvalue ::= [sign
]absfloatvalue
Case is not significant, so, for example, “inf”, “Inf”, “INFINITY”, and “iNfINity” are all acceptable spellings for positive infinity.
Otherwise, if the argument is an integer or a floating-point number, a floating-point number with the same value (within Python’s floating-point precision) is returned. If the argument is outside the range of a Python float, an
OverflowError
will be raised.For a general Python object
x
,float(x)
delegates tox.__float__()
. If__float__()
is not defined then it falls back to__index__()
.If no argument is given,
0.0
is returned.The float type is described in Numeric Types — int, float, complex.
Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.
Changed in version 3.7: The parameter is now positional-only.
Changed in version 3.8: Falls back to
__index__()
if__float__()
is not defined.
- format(value, format_spec='', /)¶
Convert a value to a “formatted” representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument; however, there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language.
The default format_spec is an empty string which usually gives the same effect as calling
str(value)
.A call to
format(value, format_spec)
is translated totype(value).__format__(value, format_spec)
which bypasses the instance dictionary when searching for the value’s__format__()
method. ATypeError
exception is raised if the method search reachesobject
and the format_spec is non-empty, or if either the format_spec or the return value are not strings.Changed in version 3.4:
object().__format__(format_spec)
raisesTypeError
if format_spec is not an empty string.
- class frozenset(iterable=(), /)
Return a new
frozenset
object, optionally with elements taken from iterable.frozenset
is a built-in class. Seefrozenset
and Set Types — set, frozenset for documentation about this class.For other containers see the built-in
set
,list
,tuple
, anddict
classes, as well as thecollections
module.
- getattr(object, name, /)¶
- getattr(object, name, default, /)
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example,
getattr(x, 'foobar')
is equivalent tox.foobar
. If the named attribute does not exist, default is returned if provided, otherwiseAttributeError
is raised. name need not be a Python identifier (seesetattr()
).Note
Since private name mangling happens at compilation time, one must manually mangle a private attribute’s (attributes with two leading underscores) name in order to retrieve it with
getattr()
.
- globals()¶
Return the dictionary implementing the current module namespace. For code within functions, this is set when the function is defined and remains the same regardless of where the function is called.
- hasattr(object, name, /)¶
The arguments are an object and a string. The result is
True
if the string is the name of one of the object’s attributes,False
if not. (This is implemented by callinggetattr(object, name)
and seeing whether it raises anAttributeError
or not.)
- hash(object, /)¶
Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).
Note
For objects with custom
__hash__()
methods, note thathash()
truncates the return value based on the bit width of the host machine.
- help()¶
- help(request)
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
Note that if a slash(/) appears in the parameter list of a function when invoking
help()
, it means that the parameters prior to the slash are positional-only. For more info, see the FAQ entry on positional-only parameters.This function is added to the built-in namespace by the
site
module.
- hex(integer, /)¶
Convert an integer number to a lowercase hexadecimal string prefixed with “0x”. If integer is not a Python
int
object, it has to define an__index__()
method that returns an integer. Some examples:>>> hex(255) '0xff' >>> hex(-42) '-0x2a'
If you want to convert an integer number to an uppercase or lower hexadecimal string with prefix or not, you can use either of the following ways:
>>> '%#x' % 255, '%x' % 255, '%X' % 255 ('0xff', 'ff', 'FF') >>> format(255, '#x'), format(255, 'x'), format(255, 'X') ('0xff', 'ff', 'FF') >>> f'{255:#x}', f'{255:x}', f'{255:X}' ('0xff', 'ff', 'FF')
See also
format()
for more information.See also
int()
for converting a hexadecimal string to an integer using a base of 16.Note
To obtain a hexadecimal string representation for a float, use the
float.hex()
method.
- id(object, /)¶
Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same
id()
value.CPython implementation detail: This is the address of the object in memory.
Raises an auditing event
builtins.id
with argumentid
.
- input()¶
- input(prompt, /)
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read,
EOFError
is raised. Example:>>> s = input('--> ') --> Monty Python's Flying Circus >>> s "Monty Python's Flying Circus"
If the
readline
module was loaded, theninput()
will use it to provide elaborate line editing and history features.Raises an auditing event
builtins.input
with argumentprompt
before reading inputRaises an auditing event
builtins.input/result
with the result after successfully reading input.
- class int(number=0, /)¶
- class int(string, /, base=10)
Return an integer object constructed from a number or a string, or return
0
if no arguments are given.Examples:
>>> int(123.45) 123 >>> int('123') 123 >>> int(' -12_345\n') -12345 >>> int('FACE', 16) 64206 >>> int('0xface', 0) 64206 >>> int('01110011', base=2) 115
If the argument defines
__int__()
,int(x)
returnsx.__int__()
. If the argument defines__index__()
, it returnsx.__index__()
. If the argument defines__trunc__()
, it returnsx.__trunc__()
. For floating-point numbers, this truncates towards zero.If the argument is not a number or if base is given, then it must be a string,
bytes
, orbytearray
instance representing an integer in radix base. Optionally, the string can be preceded by+
or-
(with no space in between), have leading zeros, be surrounded by whitespace, and have single underscores interspersed between digits.A base-n integer string contains digits, each representing a value from 0 to n-1. The values 0–9 can be represented by any Unicode decimal digit. The values 10–35 can be represented by
a
toz
(orA
toZ
). The default base is 10. The allowed bases are 0 and 2–36. Base-2, -8, and -16 strings can be optionally prefixed with0b
/0B
,0o
/0O
, or0x
/0X
, as with integer literals in code. For base 0, the string is interpreted in a similar way to an integer literal in code, in that the actual base is 2, 8, 10, or 16 as determined by the prefix. Base 0 also disallows leading zeros:int('010', 0)
is not legal, whileint('010')
andint('010', 8)
are.The integer type is described in Numeric Types — int, float, complex.
Changed in version 3.4: If base is not an instance of
int
and the base object has abase.__index__
method, that method is called to obtain an integer for the base. Previous versions usedbase.__int__
instead ofbase.__index__
.Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.
Changed in version 3.7: The first parameter is now positional-only.
Changed in version 3.8: Falls back to
__index__()
if__int__()
is not defined.Changed in version 3.11: The delegation to
__trunc__()
is deprecated.Changed in version 3.11:
int
string inputs and string representations can be limited to help avoid denial of service attacks. AValueError
is raised when the limit is exceeded while converting a string to anint
or when converting anint
into a string would exceed the limit. See the integer string conversion length limitation documentation.
- isinstance(object, classinfo, /)¶
Return
True
if the object argument is an instance of the classinfo argument, or of a (direct, indirect, or virtual) subclass thereof. If object is not an object of the given type, the function always returnsFalse
. If classinfo is a tuple of type objects (or recursively, other such tuples) or a Union Type of multiple types, returnTrue
if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, aTypeError
exception is raised.TypeError
may not be raised for an invalid type if an earlier check succeeds.Changed in version 3.10: classinfo can be a Union Type.
- issubclass(class, classinfo, /)¶
Return
True
if class is a subclass (direct, indirect, or virtual) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects (or recursively, other such tuples) or a Union Type, in which case returnTrue
if class is a subclass of any entry in classinfo. In any other case, aTypeError
exception is raised.Changed in version 3.10: classinfo can be a Union Type.
- iter(iterable, /)¶
- iter(callable, sentinel, /)
Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, the single argument must be a collection object which supports the iterable protocol (the
__iter__()
method), or it must support the sequence protocol (the__getitem__()
method with integer arguments starting at0
). If it does not support either of those protocols,TypeError
is raised. If the second argument, sentinel, is given, then the first argument must be a callable object. The iterator created in this case will call callable with no arguments for each call to its__next__()
method; if the value returned is equal to sentinel,StopIteration
will be raised, otherwise the value will be returned.See also Iterator Types.
One useful application of the second form of
iter()
is to build a block-reader. For example, reading fixed-width blocks from a binary database file until the end of file is reached:from functools import partial with open('mydata.db', 'rb') as f: for block in iter(partial(f.read, 64), b''): process_block(block)
- len(object, /)¶
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
CPython implementation detail:
len
raisesOverflowError
on lengths larger thansys.maxsize
, such asrange(2 ** 100)
.