Teks sumber — English
Terjemahan — Bahasa Indonesia
There are three distinct numeric types: :dfn:`integers`, :dfn:`floating-point numbers`, and :dfn:`complex numbers`. In addition, Booleans are a subtype of integers. Integers have unlimited precision. Floating-point numbers are usually implemented using :c:expr:`double` in C; information about the precision and internal representation of floating-point numbers for the machine on which your program is running is available in :data:`sys.float_info`. Complex numbers have a real and imaginary part, which are each a floating-point number. To extract these parts from a complex number *z*, use ``z.real`` and ``z.imag``. (The standard library includes the additional numeric types :mod:`fractions.Fraction`, for rationals, and :mod:`decimal.Decimal`, for floating-point numbers with user-definable precision.)
where the optional ``sign`` may be either ``+`` or ``-``, ``integer`` and ``fraction`` are strings of hexadecimal digits, and ``exponent`` is a decimal integer with an optional leading sign. Case is not significant, and there must be at least one hexadecimal digit in either the integer or the fraction. This syntax is similar to the syntax specified in section 6.4.4.2 of the C99 standard, and also to the syntax used in Java 1.5 onwards. In particular, the output of :meth:`float.hex` is usable as a hexadecimal floating-point literal in C or Java code, and hexadecimal strings produced by C's ``%a`` format character or Java's ``Double.toHexString`` are accepted by :meth:`float.fromhex`.
For detailed information on thread-safety guarantees for :class:`list` objects, see :ref:`thread-safety-list`.
Tuples are :ref:`generic <generics>` over the types of their contents. For more information, refer to :ref:`the typing documentation on annotating tuples <annotating-tuples>`.
Formatting
:meth:`str.format`
:meth:`str.format_map`
:ref:`old-string-formatting`
:ref:`old-string-formatting`
:ref:`bytes-formatting`
If at least one of *encoding* or *errors* is given, *object* should be a :term:`bytes-like object` (e.g. :class:`bytes` or :class:`bytearray`). In this case, if *object* is a :class:`bytes` (or :class:`bytearray`) object, then ``str(bytes, encoding, errors)`` is equivalent to :meth:`bytes.decode(encoding, errors) <bytes.decode>`. Otherwise, the bytes object underlying the buffer object is obtained before calling :meth:`bytes.decode`. See :ref:`binaryseq` and :ref:`bufferobjects` for information on buffer objects.
For more information on the ``str`` class and its methods, see :ref:`textseq` and the :ref:`string-methods` section below. To output formatted strings, see the :ref:`f-strings` and :ref:`formatstrings` sections. In addition, see the :ref:`stringservices` section.
Strings also support two styles of string formatting, one providing a large degree of flexibility and customization (see :meth:`str.format`, :ref:`formatstrings` and :ref:`string-formatting`) and the other based on C ``printf`` style formatting that handles a narrower range of types and is slightly harder to use correctly, but is often faster for the cases it can handle (:ref:`old-string-formatting`).
Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces ``{}``. Each replacement field refers to a positional argument (numbered explicitly or automatically) or a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument. For example:
>>> "The sum of {} + {} is {}".format(1, 2, 1+2)
'The sum of 1 + 2 is 3'
>>> "{1} expects the {0} Inquisition!".format("Spanish", "Nobody")
'Nobody expects the Spanish Inquisition!'
>>> "The sum of {a} + {b} is {answer}".format(answer=1+2, a=1, b=2)
'The sum of 1 + 2 is 3'
See :ref:`formatstrings` for a description of the various formatting options that can be specified in format strings.
When formatting a number (:class:`int`, :class:`float`, :class:`complex`, :class:`decimal.Decimal` and subclasses) with the ``n`` type (ex: ``'{:n}'.format(1234)``), the function temporarily sets the ``LC_CTYPE`` locale to the ``LC_NUMERIC`` locale to decode ``decimal_point`` and ``thousands_sep`` fields of :c:func:`localeconv` if they are non-ASCII or longer than 1 byte, and the ``LC_NUMERIC`` locale is different than the ``LC_CTYPE`` locale. This temporary change affects other threads.
When formatting a number with the ``n`` type, the function sets temporarily the ``LC_CTYPE`` locale to the ``LC_NUMERIC`` locale in some cases.
Similar to ``str.format(**mapping)``, except that ``mapping`` is used directly and not copied to a :class:`dict`. This is useful if for example ``mapping`` is a dict subclass:
You can use :meth:`str.maketrans` to create a translation map from character-to-character mappings in different formats.
Formatted String Literals (f-strings)
An :dfn:`f-string` (formally a :dfn:`formatted string literal`) is a string literal that is prefixed with ``f`` or ``F``. This type of string literal allows embedding the results of arbitrary Python expressions within *replacement fields*, which are delimited by curly brackets (``{}``). Each replacement field must contain an expression, optionally followed by:
a *format specifier* prefixed with a colon (``:``).
When a debug specifier but no format specifier is used, the default conversion instead uses :func:`repr`::
Format specifier
After the expression has been evaluated, and possibly converted using an explicit conversion specifier, it is formatted using the :func:`format` function. If the replacement field includes a *format specifier* introduced by a colon (``:``), the specifier is passed to :func:`!format` as the second argument. The result of :func:`!format` is then used as the final value for the replacement field. For example::
These strings follow the same syntax and evaluation rules as :ref:`formatted string literals <stdtypes-fstrings>`, with the following differences:
The :func:`format` protocol is not used. Instead, the format specifier and conversions (if any) are passed to a new :class:`~string.templatelib.Interpolation` object that is created for each evaluated expression. It is up to code that processes the resulting :class:`~string.templatelib.Template` object to decide how to handle format specifiers and conversions.
Format specifiers containing nested replacement fields are evaluated eagerly, prior to being passed to the :class:`~string.templatelib.Interpolation` object. For instance, an interpolation of the form ``{amount:.{precision}f}`` will evaluate the inner expression ``{precision}`` to determine the value of the ``format_spec`` attribute. If ``precision`` were to be ``2``, the resulting format specifier would be ``'.2f'``.
When the equals sign ``'='`` is provided in an interpolation expression, the text of the expression is appended to the literal string that precedes the relevant interpolation. This includes the equals sign and any surrounding whitespace. The :class:`!Interpolation` instance for the expression will be created as normal, except that :attr:`~string.templatelib.Interpolation.conversion` will be set to '``r``' (:func:`repr`) by default. If an explicit conversion or format specifier is provided, this will override the default behaviour.
``printf``-style String Formatting
The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly).
Using :ref:`formatted string literals <f-strings>`, the :meth:`str.format` interface, or :class:`string.Template` may help avoid these errors. Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility.
String 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), ``%`` conversion specifications in *format* are replaced with zero or more elements of *values*. The effect is similar to using the :c:func:`sprintf` function in the C language. For example:
If *format* requires a single argument, *values* may be a single non-tuple object. [5]_ 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).
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:
In this case no ``*`` specifiers may occur in a format (since they require a sequential parameter list).
Floating-point exponential format (lowercase).
Floating-point exponential format (uppercase).
Floating-point decimal format.
Floating-point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.
Floating-point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.
For floating-point formats, the result should be correctly rounded to the specified precision. The rounding mode matches that of the :func:`round` builtin.
The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether the ``'x'`` or ``'X'`` format was used) to be inserted before the first digit.
While bytes literals and representations are based on ASCII text, bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that ``0 <= x < 256`` (attempts to violate this restriction will trigger :exc:`ValueError`). This is done deliberately to emphasise that while many binary formats include ASCII based elements and can be usefully manipulated with some text-oriented algorithms, this is not generally the case for arbitrary binary data (blindly applying text processing algorithms to binary data formats that are not ASCII compatible will usually lead to data corruption).
Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data. Accordingly, the bytes type has an additional class method to read data in that format:
The representation of bytes objects uses the literal format (``b'...'``) since it is often more useful than e.g. ``bytes([46, 46, 46])``. You can always convert a bytes object into a list of integers using ``list(b)``.
Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data. Accordingly, the bytearray type has an additional class method to read data in that format:
The representation of bytearray objects uses the bytes literal format (``bytearray(b'...')``) since it is often more useful than e.g. ``bytearray([46, 46, 46])``. You can always convert a bytearray object into a list of integers using ``list(b)``.
For detailed information on thread-safety guarantees for :class:`bytearray` objects, see :ref:`thread-safety-bytearray`.
Some bytes and bytearray operations assume the use of ASCII compatible binary formats, and hence should be avoided when working with arbitrary binary data. These restrictions are covered below.
Using these ASCII based operations to manipulate binary data that is not stored in an ASCII based format may lead to data corruption.
The following methods on bytes and bytearray objects have default behaviours that assume the use of ASCII compatible binary formats, but can still be used with arbitrary binary data by passing appropriate arguments. Note that all of the bytearray methods in this section do *not* operate in place, and instead produce new objects.
The following methods on bytes and bytearray objects assume the use of ASCII compatible binary formats and should not be applied to arbitrary binary data. Note that all of the bytearray methods in this section do *not* operate in place, and instead produce new objects.
``printf``-style Bytes Formatting
The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). If the value being printed may be a tuple or dictionary, wrap it in a tuple.
Bytes objects (``bytes``/``bytearray``) have one unique built-in operation: the ``%`` operator (modulo). This is also known as the bytes *formatting* or *interpolation* operator. Given ``format % values`` (where *format* is a bytes object), ``%`` conversion specifications in *format* are replaced with zero or more elements of *values*. The effect is similar to using the :c:func:`sprintf` function in the C language.
If *format* requires a single argument, *values* may be a single non-tuple object. [5]_ Otherwise, *values* must be a tuple with exactly the number of items specified by the format bytes object, or a single mapping object (for example, a dictionary).
When the right argument is a dictionary (or other mapping type), then the formats in the bytes object *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:
:pep:`461` - Adding % formatting to bytes and bytearray
If :class:`~memoryview.format` is one of the native format specifiers from the :mod:`struct` module, indexing with an integer or a tuple of integers is also supported and returns a single *element* with the correct type. One-dimensional memoryviews can be indexed with an integer or a one-integer tuple. Multi-dimensional memoryviews can be indexed with tuples of exactly *ndim* integers where *ndim* is the number of dimensions. Zero-dimensional memoryviews can be indexed with the empty tuple.
Here is an example with a non-byte format::
One-dimensional memoryviews of :term:`hashable` (read-only) types with formats 'B', 'b' or 'c' are also hashable. The hash is defined as ``hash(m) == hash(m.tobytes())``::
One-dimensional memoryviews can now be sliced. One-dimensional memoryviews with formats 'B', 'b' or 'c' are now :term:`hashable`.
A memoryview and a :pep:`3118` exporter are equal if their shapes are equivalent and if all corresponding values are equal when the operands' respective format codes are interpreted using :mod:`struct` syntax.
For the subset of :mod:`struct` format strings currently supported by :meth:`tolist`, ``v`` and ``w`` are equal if ``v.tolist() == w.tolist()``::
If either format string is not supported by the :mod:`struct` module, then the objects will always compare as unequal (even if the format strings and buffer contents are identical)::
Previous versions compared the raw memory disregarding the item format and the logical array structure.
For non-contiguous arrays the result is equal to the flattened list representation with all elements converted to bytes. :meth:`tobytes` supports all format strings, including those that are not in :mod:`struct` module syntax.
:meth:`tolist` now supports all single character native formats in :mod:`struct` module syntax as well as multi-dimensional representations.
Cast a memoryview to a new format or shape. *shape* defaults to ``[byte_length//new_itemsize]``, which means that the result view will be one-dimensional. The return value is a new memoryview, but the buffer itself is not copied. Supported casts are 1D -> C-:term:`contiguous` and C-contiguous -> 1D.
The destination format is restricted to a single element native format in :mod:`struct` syntax. One of the formats must be a byte format ('B', 'b' or 'c'). The byte length of the result must be the same as the original length. Note that all byte lengths may depend on the operating system.
>>> import array
>>> a = array.array('l', [1,2,3])
>>> x = memoryview(a)
>>> x.format
'l'
>>> x.itemsize
8
>>> len(x)
3
>>> x.nbytes
24
>>> y = x.cast('B')
>>> y.format
'B'
>>> y.itemsize
1
>>> len(y)
24
>>> y.nbytes
24
>>> b = bytearray(b'zyz')
>>> x = memoryview(b)
>>> x[0] = b'a'
Traceback (most recent call last):
...
TypeError: memoryview: invalid type for format 'B'
>>> y = x.cast('c')
>>> y[0] = b'a'
>>> b
bytearray(b'ayz')
>>> import struct
>>> buf = struct.pack("i"*12, *list(range(12)))
>>> x = memoryview(buf)
>>> y = x.cast('i', shape=[2,2,3])
>>> y.tolist()
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]
>>> y.format
'i'
>>> y.itemsize
4
>>> len(y)
2
>>> y.nbytes
48
>>> z = y.cast('b')
>>> z.format
'b'
>>> z.itemsize
1
>>> len(z)
48
>>> z.nbytes
48
The source format is no longer restricted when casting to a byte view.
A string containing the format (in :mod:`struct` module style) for each element in the view. A memoryview can be created from exporters with arbitrary format strings, but some methods (e.g. :meth:`tolist`) are restricted to native single element formats.
format ``'B'`` is now handled according to the struct module syntax. This means that ``memoryview(b'abc')[0] == b'abc'[0] == 97``.
Used internally for PIL-style arrays. The value is informational only.
For information on the thread safety of :class:`memoryview` objects in the :term:`free-threaded build`, see :ref:`thread-safety-memoryview`.
For detailed information on thread-safety guarantees for :class:`set` objects, see :ref:`thread-safety-set`.
For detailed information on thread-safety guarantees for :class:`dict` objects, see :ref:`thread-safety-dict`.
Exit the runtime context and return a Boolean flag indicating if any exception that occurred should be suppressed. If an exception occurred while executing the body of the :keyword:`with` statement, the arguments contain the exception type, value and traceback information. Otherwise, all three arguments are ``None``.
See :ref:`function` for more information.
See :ref:`instance-methods` for more information.
See :ref:`types` for more information.
This object is returned from comparisons and binary operations when they are asked to operate on types they don't support. See :ref:`comparisons` for more information. There is exactly one :data:`NotImplemented` object. :code:`type(NotImplemented)()` produces the singleton instance.
See :ref:`types` for this information. It describes :ref:`stack frame objects <frame-objects>`, :ref:`traceback objects <traceback-objects>`, and slice objects.
any other string conversion to base 10, for example ``f"{integer}"``, ``"{}".format(integer)``, or ``b"%d" % integer``.
:ref:`formatspec` for hex, octal, and binary numbers.
Information about the default and minimum can be found in :data:`sys.int_info`:
Additional information on these special methods may be found in the Python Reference Manual (:ref:`customization`).
To format only a tuple you should therefore provide a singleton tuple whose only element is the tuple to be formatted.
Untuk memformat hanya *tuple*, Anda harus menyediakan *tuple* *singleton* dimana elemennya hanya *tuple* yang akan diformat.
! formatted string literal
formatted string literals
formatted literal
in formatted string literal
formatting, string (%)
formatting, printf
printf-style formatting
sprintf-style formatting
in printf-style formatting
formatting