The binascii module contains a number of methods to convert between binary and various ASCII-encoded binary representations. Normally, you will not use these functions directly but use wrapper modules like uu, base64, or binhex instead. The binascii module contains low-level functions written in C for greater speed that are used by the higher-level modules.
Note
a2b_* functions accept Unicode strings containing only ASCII characters. Other functions only accept bytes-like objects (such as bytes, bytearray and other objects that support the buffer protocol).
Changed in version 3.3: ASCII-only unicode strings are now accepted by the a2b_* functions.
The binascii module defines the following functions:
Convert a single line of uuencoded data back to binary and return the binary data. Lines normally contain 45 (binary) bytes, except for the last line. Line data may be followed by whitespace.
Convert binary data to a line of ASCII characters, the return value is the converted line, including a newline char. The length of data should be at most 45. If backtick is true, zeros are represented by '`' instead of spaces.
Changed in version 3.7: Added the backtick parameter.
Convert a block of base64 data back to binary and return the binary data. More than one line may be passed at a time.
Convert binary data to a line of ASCII characters in base64 coding. The return value is the converted line, including a newline char if newline is true. The output of this function conforms to RFC 3548.
Changed in version 3.6: Added the newline parameter.
Convert a block of quoted-printable data back to binary and return the binary data. More than one line may be passed at a time. If the optional argument header is present and true, underscores will be decoded as spaces.
Convert binary data to a line(s) of ASCII characters in quoted-printable encoding. The return value is the converted line(s). If the optional argument quotetabs is present and true, all tabs and spaces will be encoded. If the optional argument istext is present and true, newlines are not encoded but trailing whitespace will be encoded. If the optional argument header is present and true, spaces will be encoded as underscores per RFC 1522. If the optional argument header is present and false, newline characters will be encoded as well; otherwise linefeed conversion might corrupt the binary data stream.
Convert binhex4 formatted ASCII data to binary, without doing RLE-decompression. The string should contain a complete number of binary bytes, or (in case of the last portion of the binhex4 data) have the remaining bits zero.
Deprecated since version 3.9.
Perform RLE-decompression on the data, as per the binhex4 standard. The algorithm uses 0x90 after a byte as a repeat indicator, followed by a count. A count of 0 specifies a byte value of 0x90. The routine returns the decompressed data, unless data input data ends in an orphaned repeat indicator, in which case the Incomplete exception is raised.
Changed in version 3.2: Accept only bytestring or bytearray objects as input.
Deprecated since version 3.9.
Perform binhex4 style RLE-compression on data and return the result.
Deprecated since version 3.9.
Perform hexbin4 binary-to-ASCII translation and return the resulting string. The argument should already be RLE-coded, and have a length divisible by 3 (except possibly the last fragment).
Deprecated since version 3.9.
Compute a 16-bit CRC value of data, starting with value as the initial CRC, and return the result. This uses the CRC-CCITT polynomial x16 + x12 + x5 + 1, often represented as 0x1021. This CRC is used in the binhex4 format.
Compute CRC-32, the 32-bit checksum of data, starting with an initial CRC of value. The default initial CRC is zero. The algorithm is consistent with the ZIP file checksum. Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm. Use as follows:
Changed in version 3.0: The result is always unsigned. To generate the same numeric value across all Python versions and platforms, use crc32(data) & 0xffffffff.
Return the hexadecimal representation of the binary data. Every byte of data is converted into the corresponding 2-digit hex representation. The returned bytes object is therefore twice as long as the length of data.
Similar functionality (but returning a text string) is also conveniently accessible using the bytes.hex() method.
If sep is specified, it must be a single character str or bytes object. It will be inserted in the output after every bytes_per_sep input bytes. Separator placement is counted from the right end of the output by default, if you wish to count from the left, supply a negative bytes_per_sep value.
Changed in version 3.8: The sep and bytes_per_sep parameters were added.
Return the binary data represented by the hexadecimal string hexstr. This function is the inverse of b2a_hex(). hexstr must contain an even number of hexadecimal digits (which can be upper or lower case), otherwise an Error exception is raised.
Similar functionality (accepting only text string arguments, but more liberal towards whitespace) is also accessible using the bytes.fromhex() class method.
Exception raised on errors. These are usually programming errors.
Exception raised on incomplete data. These are usually not programming errors, but may be handled by reading a little more data and trying again.
See also
Support for RFC compliant base64-style encoding in base 16, 32, 64, and 85.
Support for the binhex format used on the Macintosh.
Support for UU encoding used on Unix.
Support for quoted-printable encoding used in MIME email messages.


Convert a block of base64 data back to binary and return the binary data. More than one line may be passed at a time.


Return the binary data represented by the hexadecimal string hexstr. This function is the inverse of b2a_hex(). hexstr must contain an even number of hexadecimal digits (which can be upper or lower case), otherwise an Error exception is raised.
Similar functionality (accepting only text string arguments, but more liberal towards whitespace) is also accessible using the bytes.fromhex() class method.


Convert binhex4 formatted ASCII data to binary, without doing RLE-decompression. The string should contain a complete number of binary bytes, or (in case of the last portion of the binhex4 data) have the remaining bits zero.
Deprecated since version 3.9.


Convert a block of quoted-printable data back to binary and return the binary data. More than one line may be passed at a time. If the optional argument header is present and true, underscores will be decoded as spaces.


Convert a single line of uuencoded data back to binary and return the binary data. Lines normally contain 45 (binary) bytes, except for the last line. Line data may be followed by whitespace.


Convert binary data to a line of ASCII characters in base64 coding. The return value is the converted line, including a newline char if newline is true. The output of this function conforms to RFC 3548.
Changed in version 3.6: Added the newline parameter.


Return the hexadecimal representation of the binary data. Every byte of data is converted into the corresponding 2-digit hex representation. The returned bytes object is therefore twice as long as the length of data.
Similar functionality (but returning a text string) is also conveniently accessible using the bytes.hex() method.
If sep is specified, it must be a single character str or bytes object. It will be inserted in the output after every bytes_per_sep input bytes. Separator placement is counted from the right end of the output by default, if you wish to count from the left, supply a negative bytes_per_sep value.
Changed in version 3.8: The sep and bytes_per_sep parameters were added.


Perform hexbin4 binary-to-ASCII translation and return the resulting string. The argument should already be RLE-coded, and have a length divisible by 3 (except possibly the last fragment).
Deprecated since version 3.9.


Convert binary data to a line(s) of ASCII characters in quoted-printable encoding. The return value is the converted line(s). If the optional argument quotetabs is present and true, all tabs and spaces will be encoded. If the optional argument istext is present and true, newlines are not encoded but trailing whitespace will be encoded. If the optional argument header is present and true, spaces will be encoded as underscores per RFC 1522. If the optional argument header is present and false, newline characters will be encoded as well; otherwise linefeed conversion might corrupt the binary data stream.


Convert binary data to a line of ASCII characters, the return value is the converted line, including a newline char. The length of data should be at most 45. If backtick is true, zeros are represented by '`' instead of spaces.
Changed in version 3.7: Added the backtick parameter.


Compute CRC-32, the 32-bit checksum of data, starting with an initial CRC of value. The default initial CRC is zero. The algorithm is consistent with the ZIP file checksum. Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm. Use as follows:
Changed in version 3.0: The result is always unsigned. To generate the same numeric value across all Python versions and platforms, use crc32(data) & 0xffffffff.


Compute a 16-bit CRC value of data, starting with value as the initial CRC, and return the result. This uses the CRC-CCITT polynomial x16 + x12 + x5 + 1, often represented as 0x1021. This CRC is used in the binhex4 format.


Exception raised on errors. These are usually programming errors.


Exception raised on incomplete data. These are usually not programming errors, but may be handled by reading a little more data and trying again.


Perform binhex4 style RLE-compression on data and return the result.
Deprecated since version 3.9.


Perform RLE-decompression on the data, as per the binhex4 standard. The algorithm uses 0x90 after a byte as a repeat indicator, followed by a count. A count of 0 specifies a byte value of 0x90. The routine returns the decompressed data, unless data input data ends in an orphaned repeat indicator, in which case the Incomplete exception is raised.
Changed in version 3.2: Accept only bytestring or bytearray objects as input.
Deprecated since version 3.9.


Source code: Lib/binhex.py
Deprecated since version 3.9.
This module encodes and decodes files in binhex4 format, a format allowing representation of Macintosh files in ASCII. Only the data fork is handled.
The binhex module defines the following functions:
Convert a binary file with filename input to binhex file output. The output parameter can either be a filename or a file-like object (any object supporting a write() and close() method).
Decode a binhex file input. input may be a filename or a file-like object supporting read() and close() methods. The resulting file is written to a file named output, unless the argument is None in which case the output filename is read from the binhex file.
The following exception is also defined:
Exception raised when something can’t be encoded using the binhex format (for example, a filename is too long to fit in the filename field), or when input is not properly encoded binhex data.
See also
Support module containing ASCII-to-binary and binary-to-ASCII conversions.
There is an alternative, more powerful interface to the coder and decoder, see the source for details.
If you code or decode textfiles on non-Macintosh platforms they will still use the old Macintosh newline convention (carriage-return as end of line).


Convert a binary file with filename input to binhex file output. The output parameter can either be a filename or a file-like object (any object supporting a write() and close() method).


Exception raised when something can’t be encoded using the binhex format (for example, a filename is too long to fit in the filename field), or when input is not properly encoded binhex data.


Decode a binhex file input. input may be a filename or a file-like object supporting read() and close() methods. The resulting file is written to a file named output, unless the argument is None in which case the output filename is read from the binhex file.


Source code: Lib/bisect.py
This module provides support for maintaining a list in sorted order without having to sort the list after each insertion. For long lists of items with expensive comparison operations, this can be an improvement over the more common approach. The module is called bisect because it uses a basic bisection algorithm to do its work. The source code may be most useful as a working example of the algorithm (the boundary conditions are already right!).
The following functions are provided:
Locate the insertion point for x in a to maintain sorted order. The parameters lo and hi may be used to specify a subset of the list which should be considered; by default the entire list is used. If x is already present in a, the insertion point will be before (to the left of) any existing entries. The return value is suitable for use as the first parameter to list.insert() assuming that a is already sorted.
The returned insertion point i partitions the array a into two halves so that all(val < x for val in a[lo:i]) for the left side and all(val >= x for val in a[i:hi]) for the right side.
Similar to bisect_left(), but returns an insertion point which comes after (to the right of) any existing entries of x in a.
The returned insertion point i partitions the array a into two halves so that all(val <= x for val in a[lo:i]) for the left side and all(val > x for val in a[i:hi]) for the right side.
Insert x in a in sorted order. This is equivalent to a.insert(bisect.bisect_left(a, x, lo, hi), x) assuming that a is already sorted. Keep in mind that the O(log n) search is dominated by the slow O(n) insertion step.
Similar to insort_left(), but inserting x in a after any existing entries of x.
See also
SortedCollection recipe that uses bisect to build a full-featured collection class with straight-forward search methods and support for a key-function. The keys are precomputed to save unnecessary calls to the key function during searches.
The above bisect() functions are useful for finding insertion points but can be tricky or awkward to use for common searching tasks. The following five functions show how to transform them into the standard lookups for sorted lists:
The bisect() function can be useful for numeric table lookups. This example uses bisect() to look up a letter grade for an exam score (say) based on a set of ordered numeric breakpoints: 90 and up is an ‘A’, 80 to 89 is a ‘B’, and so on:
Unlike the sorted() function, it does not make sense for the bisect() functions to have key or reversed arguments because that would lead to an inefficient design (successive calls to bisect functions would not “remember” all of the previous key lookups).
Instead, it is better to search a list of precomputed keys to find the index of the record in question:


Similar to bisect_left(), but returns an insertion point which comes after (to the right of) any existing entries of x in a.
The returned insertion point i partitions the array a into two halves so that all(val <= x for val in a[lo:i]) for the left side and all(val > x for val in a[i:hi]) for the right side.


Locate the insertion point for x in a to maintain sorted order. The parameters lo and hi may be used to specify a subset of the list which should be considered; by default the entire list is used. If x is already present in a, the insertion point will be before (to the left of) any existing entries. The return value is suitable for use as the first parameter to list.insert() assuming that a is already sorted.
The returned insertion point i partitions the array a into two halves so that all(val < x for val in a[lo:i]) for the left side and all(val >= x for val in a[i:hi]) for the right side.


Similar to insort_left(), but inserting x in a after any existing entries of x.


Insert x in a in sorted order. This is equivalent to a.insert(bisect.bisect_left(a, x, lo, hi), x) assuming that a is already sorted. Keep in mind that the O(log n) search is dominated by the slow O(n) insertion step.


Raised when an operation would block on an object (e.g. socket) set for non-blocking operation. Corresponds to errno EAGAIN, EALREADY, EWOULDBLOCK and EINPROGRESS.
In addition to those of OSError, BlockingIOError can have one more attribute:
An integer containing the number of characters written to the stream before it blocked. This attribute is available when using the buffered I/O classes from the io module.


An integer containing the number of characters written to the stream before it blocked. This attribute is available when using the buffered I/O classes from the io module.


Return a Boolean value, i.e. one of True or False. x is converted using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise it returns True. The bool class is a subclass of int (see Numeric Types — int, float, complex). It cannot be subclassed further. Its only instances are False and True (see Boolean Values).
Changed in version 3.7: x is now a positional-only parameter.


This function drops you into the debugger at the call site. Specifically, it calls sys.breakpointhook(), passing args and kws straight through. By default, sys.breakpointhook() calls pdb.set_trace() expecting no arguments. In this case, it is purely a convenience function so you don’t have to explicitly import pdb or type as much code to enter the debugger. However, sys.breakpointhook() can be set to some other function and breakpoint() will automatically call that, allowing you to drop into the debugger of choice.
Raises an auditing event builtins.breakpoint with argument breakpointhook.
New in version 3.7.


A subclass of ConnectionError, raised when trying to write on a pipe while the other end has been closed, or trying to write on a socket which has been shutdown for writing. Corresponds to errno EPIPE and ESHUTDOWN.


Raised when a buffer related operation cannot be performed.


This module provides direct access to all ‘built-in’ identifiers of Python; for example, builtins.open is the full name for the built-in function open(). See Built-in Functions and Built-in Constants for documentation.
This module is not normally accessed explicitly by most applications, but can be useful in modules that provide objects with the same name as a built-in value, but in which the built-in of that name is also needed. For example, in a module that wants to implement an open() function that wraps the built-in open(), this module can be used directly:
As an implementation detail, most modules have the name __builtins__ made available as part of their globals. The value of __builtins__ is normally either this module or the value of this module’s __dict__ attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.


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 the bytes type has, see Bytes and Bytearray Operations.
The optional source parameter can be used to initialize the array in a few different ways:
Without an argument, an array of size 0 is created.
See also Binary Sequence Types — bytes, bytearray, memoryview and Bytearray Objects.


There is no dedicated literal syntax for bytearray objects, instead they are always created by calling the constructor:
As bytearray objects are mutable, they support the mutable sequence operations in addition to the common bytes and bytearray operations described in Bytes and Bytearray Operations.
Also see the bytearray built-in.
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:
This bytearray class method returns bytearray object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored.
Changed in version 3.7: bytearray.fromhex() now skips all ASCII whitespace in the string, not just spaces.
A reverse conversion function exists to transform a bytearray object into its hexadecimal representation.
Return a string object containing two hexadecimal digits for each byte in the instance.
New in version 3.5.
Changed in version 3.8: Similar to bytes.hex(), bytearray.hex() now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.


Return a copy of the sequence with each byte interpreted as an ASCII character, and the first byte capitalized and the rest lowercased. Non-ASCII byte values are passed through unchanged.
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Return a copy of the object centered in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For bytes objects, the original sequence is returned if width is less than or equal to len(s).
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Return the number of non-overlapping occurrences of subsequence sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.
Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.


Return a string decoded from the given bytes. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings.
By default, the errors argument is not checked for best performances, but only used at the first decoding error. Enable the Python Development Mode, or use a debug build to check errors.
Note
Passing the encoding argument to str allows decoding any bytes-like object directly, without needing to make a temporary bytes or bytearray object.
Changed in version 3.1: Added support for keyword arguments.
Changed in version 3.9: The errors is now checked in development mode and in debug mode.


Return True if the binary data ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.
The suffix(es) to search for may be any bytes-like object.


Return a copy of the sequence where all ASCII tab characters are replaced by one or more ASCII spaces, depending on the current column and the given tab size. Tab positions occur every tabsize bytes (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the sequence, the current column is set to zero and the sequence is examined byte by byte. If the byte is an ASCII tab character (b'\t'), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied.) If the current byte is an ASCII newline (b'\n') or carriage return (b'\r'), it is copied and the current column is reset to zero. Any other byte value is copied unchanged and the current column is incremented by one regardless of how the byte value is represented when printed:
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Return the lowest index in the data where the subsequence sub is found, such that sub is contained in the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.
The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.
Note
The find() method should be used only if you need to know the position of sub. To check if sub is a substring or not, use the in operator:
Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.


This bytearray class method returns bytearray object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored.
Changed in version 3.7: bytearray.fromhex() now skips all ASCII whitespace in the string, not just spaces.


Return a string object containing two hexadecimal digits for each byte in the instance.
New in version 3.5.
Changed in version 3.8: Similar to bytes.hex(), bytearray.hex() now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.


Like find(), but raise ValueError when the subsequence is not found.
The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.
Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.


Return True if all bytes in the sequence are alphabetical ASCII characters or ASCII decimal digits and the sequence is not empty, False otherwise. Alphabetic ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'. ASCII decimal digits are those byte values in the sequence b'0123456789'.
For example:


Return True if all bytes in the sequence are alphabetic ASCII characters and the sequence is not empty, False otherwise. Alphabetic ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.
For example:


Return True if the sequence is empty or all bytes in the sequence are ASCII, False otherwise. ASCII bytes are in the range 0-0x7F.
New in version 3.7.


Return True if all bytes in the sequence are ASCII decimal digits and the sequence is not empty, False otherwise. ASCII decimal digits are those byte values in the sequence b'0123456789'.
For example:


Return True if there is at least one lowercase ASCII character in the sequence and no uppercase ASCII characters, False otherwise.
For example:
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.


Return True if all bytes in the sequence are ASCII whitespace and the sequence is not empty, False otherwise. ASCII whitespace characters are those byte values in the sequence b' \t\n\r\x0b\f' (space, tab, newline, carriage return, vertical tab, form feed).


Return True if the sequence is ASCII titlecase and the sequence is not empty, False otherwise. See bytes.title() for more details on the definition of “titlecase”.
For example:


Return True if there is at least one uppercase alphabetic ASCII character in the sequence and no lowercase ASCII characters, False otherwise.
For example:
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.


Return a bytes or bytearray object which is the concatenation of the binary data sequences in iterable. A TypeError will be raised if there are any values in iterable that are not bytes-like objects, including str objects. The separator between elements is the contents of the bytes or bytearray object providing this method.


Return a copy of the object left justified in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For bytes objects, the original sequence is returned if width is less than or equal to len(s).
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Return a copy of the sequence with all the uppercase ASCII characters converted to their corresponding lowercase counterpart.
For example:
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Return a copy of the sequence with specified leading bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or None, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped:
The binary sequence of byte values to remove may be any bytes-like object. See removeprefix() for a method that will remove a single prefix string rather than all of a set of characters. For example:
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


This static method returns a translation table usable for bytes.translate() that will map each character in from into the character at the same position in to; from and to must both be bytes-like objects and have the same length.
New in version 3.1.


Split the sequence at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing a copy of the original sequence, followed by two empty bytes or bytearray objects.
The separator to search for may be any bytes-like object.


If the binary data starts with the prefix string, return bytes[len(prefix):]. Otherwise, return a copy of the original binary data:
The prefix may be any bytes-like object.
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
New in version 3.9.


If the binary data ends with the suffix string and that suffix is not empty, return bytes[:-len(suffix)]. Otherwise, return a copy of the original binary data:
The suffix may be any bytes-like object.
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
New in version 3.9.


Return a copy of the sequence with all occurrences of subsequence old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
The subsequence to search for and its replacement may be any bytes-like object.
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Return the highest index in the sequence where the subsequence sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.
The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.
Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.


Like rfind() but raises ValueError when the subsequence sub is not found.
The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.
Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.


Return a copy of the object right justified in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For bytes objects, the original sequence is returned if width is less than or equal to len(s).
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Split the sequence at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty bytes or bytearray objects, followed by a copy of the original sequence.
The separator to search for may be any bytes-like object.


Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any subsequence consisting solely of ASCII whitespace is a separator. Except for splitting from the right, rsplit() behaves like split() which is described in detail below.


Return a copy of the sequence with specified trailing bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or None, the chars argument defaults to removing ASCII whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped:
The binary sequence of byte values to remove may be any bytes-like object. See removesuffix() for a method that will remove a single suffix string rather than all of a set of characters. For example:
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given and non-negative, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or is -1, then there is no limit on the number of splits (all possible splits are made).
If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty subsequences (for example, b'1,,2'.split(b',') returns [b'1', b'', b'2']). The sep argument may consist of a multibyte sequence (for example, b'1<>2<>3'.split(b'<>') returns [b'1', b'2', b'3']). Splitting an empty sequence with a specified separator returns [b''] or [bytearray(b'')] depending on the type of object being split. The sep argument may be any bytes-like object.
For example:
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive ASCII whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the sequence has leading or trailing whitespace. Consequently, splitting an empty sequence or a sequence consisting solely of ASCII whitespace without a specified separator returns [].
For example:


Return a list of the lines in the binary sequence, breaking at ASCII line boundaries. This method uses the universal newlines approach to splitting lines. Line breaks are not included in the resulting list unless keepends is given and true.
For example:
Unlike split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:


Return True if the binary data starts with the specified prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.
The prefix(es) to search for may be any bytes-like object.


Return a copy of the sequence with specified leading and trailing bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or None, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:
The binary sequence of byte values to remove may be any bytes-like object.
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Return a copy of the sequence with all the lowercase ASCII characters converted to their corresponding uppercase counterpart and vice-versa.
For example:
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
Unlike str.swapcase(), it is always the case that bin.swapcase().swapcase() == bin for the binary versions. Case conversions are symmetrical in ASCII, even though that is not generally true for arbitrary Unicode code points.
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Return a titlecased version of the binary sequence where words start with an uppercase ASCII character and the remaining characters are lowercase. Uncased byte values are left unmodified.
For example:
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. All other byte values are uncased.
The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:
A workaround for apostrophes can be constructed using regular expressions:
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Return a copy of the bytes or bytearray object where all bytes occurring in the optional argument delete are removed, and the remaining bytes have been mapped through the given translation table, which must be a bytes object of length 256.
You can use the bytes.maketrans() method to create a translation table.
Set the table argument to None for translations that only delete characters:
Changed in version 3.6: delete is now supported as a keyword argument.


Return a copy of the sequence with all the lowercase ASCII characters converted to their corresponding uppercase counterpart.
For example:
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Return a copy of the sequence left filled with ASCII b'0' digits to make a sequence of length width. A leading sign prefix (b'+'/ b'-') is handled by inserting the padding after the sign character rather than before. For bytes objects, the original sequence is returned if width is less than or equal to len(seq).
For example:
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Firstly, the syntax for bytes literals is largely the same as that for string literals, except that a b prefix is added:
Only ASCII characters are permitted in bytes literals (regardless of the declared source code encoding). Any binary values over 127 must be entered into bytes literals using the appropriate escape sequence.
As with string literals, bytes literals may also use a r prefix to disable processing of escape sequences. See String and Bytes literals for more about the various forms of bytes literal, including supported escape sequences.
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 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).
In addition to the literal forms, bytes objects can be created in a number of other ways:
Also see the bytes built-in.
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:
This bytes class method returns a bytes object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored.
Changed in version 3.7: bytes.fromhex() now skips all ASCII whitespace in the string, not just spaces.
A reverse conversion function exists to transform a bytes object into its hexadecimal representation.
Return a string object containing two hexadecimal digits for each byte in the instance.
If you want to make the hex string easier to read, you can specify a single character separator sep parameter to include in the output. By default between each byte. A second optional bytes_per_sep parameter controls the spacing. Positive values calculate the separator position from the right, negative values from the left.
New in version 3.5.
Changed in version 3.8: bytes.hex() now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.


Return a new “bytes” object, which is an immutable sequence of integers in the range 0 <= x < 256. bytes is an immutable version of bytearray – 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.


Return a copy of the sequence with each byte interpreted as an ASCII character, and the first byte capitalized and the rest lowercased. Non-ASCII byte values are passed through unchanged.
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Return a copy of the object centered in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For bytes objects, the original sequence is returned if width is less than or equal to len(s).
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Return the number of non-overlapping occurrences of subsequence sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.
Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.


Return a string decoded from the given bytes. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings.
By default, the errors argument is not checked for best performances, but only used at the first decoding error. Enable the Python Development Mode, or use a debug build to check errors.
Note
Passing the encoding argument to str allows decoding any bytes-like object directly, without needing to make a temporary bytes or bytearray object.
Changed in version 3.1: Added support for keyword arguments.
Changed in version 3.9: The errors is now checked in development mode and in debug mode.


Return True if the binary data ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.
The suffix(es) to search for may be any bytes-like object.


Return a copy of the sequence where all ASCII tab characters are replaced by one or more ASCII spaces, depending on the current column and the given tab size. Tab positions occur every tabsize bytes (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the sequence, the current column is set to zero and the sequence is examined byte by byte. If the byte is an ASCII tab character (b'\t'), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied.) If the current byte is an ASCII newline (b'\n') or carriage return (b'\r'), it is copied and the current column is reset to zero. Any other byte value is copied unchanged and the current column is incremented by one regardless of how the byte value is represented when printed:
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Return the lowest index in the data where the subsequence sub is found, such that sub is contained in the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.
The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.
Note
The find() method should be used only if you need to know the position of sub. To check if sub is a substring or not, use the in operator:
Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.


This bytes class method returns a bytes object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored.
Changed in version 3.7: bytes.fromhex() now skips all ASCII whitespace in the string, not just spaces.


Return a string object containing two hexadecimal digits for each byte in the instance.
If you want to make the hex string easier to read, you can specify a single character separator sep parameter to include in the output. By default between each byte. A second optional bytes_per_sep parameter controls the spacing. Positive values calculate the separator position from the right, negative values from the left.
New in version 3.5.
Changed in version 3.8: bytes.hex() now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.


Like find(), but raise ValueError when the subsequence is not found.
The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.
Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.


Return True if all bytes in the sequence are alphabetical ASCII characters or ASCII decimal digits and the sequence is not empty, False otherwise. Alphabetic ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'. ASCII decimal digits are those byte values in the sequence b'0123456789'.
For example:


Return True if all bytes in the sequence are alphabetic ASCII characters and the sequence is not empty, False otherwise. Alphabetic ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.
For example:


Return True if the sequence is empty or all bytes in the sequence are ASCII, False otherwise. ASCII bytes are in the range 0-0x7F.
New in version 3.7.


Return True if all bytes in the sequence are ASCII decimal digits and the sequence is not empty, False otherwise. ASCII decimal digits are those byte values in the sequence b'0123456789'.
For example:


Return True if there is at least one lowercase ASCII character in the sequence and no uppercase ASCII characters, False otherwise.
For example:
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.


Return True if all bytes in the sequence are ASCII whitespace and the sequence is not empty, False otherwise. ASCII whitespace characters are those byte values in the sequence b' \t\n\r\x0b\f' (space, tab, newline, carriage return, vertical tab, form feed).


Return True if the sequence is ASCII titlecase and the sequence is not empty, False otherwise. See bytes.title() for more details on the definition of “titlecase”.
For example:


Return True if there is at least one uppercase alphabetic ASCII character in the sequence and no lowercase ASCII characters, False otherwise.
For example:
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.


Return a bytes or bytearray object which is the concatenation of the binary data sequences in iterable. A TypeError will be raised if there are any values in iterable that are not bytes-like objects, including str objects. The separator between elements is the contents of the bytes or bytearray object providing this method.


Return a copy of the object left justified in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For bytes objects, the original sequence is returned if width is less than or equal to len(s).
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Return a copy of the sequence with all the uppercase ASCII characters converted to their corresponding lowercase counterpart.
For example:
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Return a copy of the sequence with specified leading bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or None, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped:
The binary sequence of byte values to remove may be any bytes-like object. See removeprefix() for a method that will remove a single prefix string rather than all of a set of characters. For example:
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


This static method returns a translation table usable for bytes.translate() that will map each character in from into the character at the same position in to; from and to must both be bytes-like objects and have the same length.
New in version 3.1.


Split the sequence at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing a copy of the original sequence, followed by two empty bytes or bytearray objects.
The separator to search for may be any bytes-like object.


If the binary data starts with the prefix string, return bytes[len(prefix):]. Otherwise, return a copy of the original binary data:
The prefix may be any bytes-like object.
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
New in version 3.9.


If the binary data ends with the suffix string and that suffix is not empty, return bytes[:-len(suffix)]. Otherwise, return a copy of the original binary data:
The suffix may be any bytes-like object.
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
New in version 3.9.


Return a copy of the sequence with all occurrences of subsequence old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
The subsequence to search for and its replacement may be any bytes-like object.
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Return the highest index in the sequence where the subsequence sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.
The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.
Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.


Like rfind() but raises ValueError when the subsequence sub is not found.
The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.
Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.


Return a copy of the object right justified in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For bytes objects, the original sequence is returned if width is less than or equal to len(s).
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Split the sequence at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty bytes or bytearray objects, followed by a copy of the original sequence.
The separator to search for may be any bytes-like object.


Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any subsequence consisting solely of ASCII whitespace is a separator. Except for splitting from the right, rsplit() behaves like split() which is described in detail below.


Return a copy of the sequence with specified trailing bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or None, the chars argument defaults to removing ASCII whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped:
The binary sequence of byte values to remove may be any bytes-like object. See removesuffix() for a method that will remove a single suffix string rather than all of a set of characters. For example:
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given and non-negative, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or is -1, then there is no limit on the number of splits (all possible splits are made).
If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty subsequences (for example, b'1,,2'.split(b',') returns [b'1', b'', b'2']). The sep argument may consist of a multibyte sequence (for example, b'1<>2<>3'.split(b'<>') returns [b'1', b'2', b'3']). Splitting an empty sequence with a specified separator returns [b''] or [bytearray(b'')] depending on the type of object being split. The sep argument may be any bytes-like object.
For example:
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive ASCII whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the sequence has leading or trailing whitespace. Consequently, splitting an empty sequence or a sequence consisting solely of ASCII whitespace without a specified separator returns [].
For example:


Return a list of the lines in the binary sequence, breaking at ASCII line boundaries. This method uses the universal newlines approach to splitting lines. Line breaks are not included in the resulting list unless keepends is given and true.
For example:
Unlike split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:


Return True if the binary data starts with the specified prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.
The prefix(es) to search for may be any bytes-like object.


Return a copy of the sequence with specified leading and trailing bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or None, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:
The binary sequence of byte values to remove may be any bytes-like object.
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Return a copy of the sequence with all the lowercase ASCII characters converted to their corresponding uppercase counterpart and vice-versa.
For example:
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
Unlike str.swapcase(), it is always the case that bin.swapcase().swapcase() == bin for the binary versions. Case conversions are symmetrical in ASCII, even though that is not generally true for arbitrary Unicode code points.
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Return a titlecased version of the binary sequence where words start with an uppercase ASCII character and the remaining characters are lowercase. Uncased byte values are left unmodified.
For example:
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. All other byte values are uncased.
The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:
A workaround for apostrophes can be constructed using regular expressions:
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Return a copy of the bytes or bytearray object where all bytes occurring in the optional argument delete are removed, and the remaining bytes have been mapped through the given translation table, which must be a bytes object of length 256.
You can use the bytes.maketrans() method to create a translation table.
Set the table argument to None for translations that only delete characters:
Changed in version 3.6: delete is now supported as a keyword argument.


Return a copy of the sequence with all the lowercase ASCII characters converted to their corresponding uppercase counterpart.
For example:
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Return a copy of the sequence left filled with ASCII b'0' digits to make a sequence of length width. A leading sign prefix (b'+'/ b'-') is handled by inserting the padding after the sign character rather than before. For bytes objects, the original sequence is returned if width is less than or equal to len(seq).
For example:
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


Base class for warnings related to bytes and bytearray.


Source code: Lib/bz2.py
This module provides a comprehensive interface for compressing and decompressing data using the bzip2 compression algorithm.
The bz2 module contains:
All of the classes in this module may safely be accessed from multiple threads.
Open a bzip2-compressed file in binary or text mode, returning a file object.
As with the constructor for BZ2File, the filename argument can be an actual filename (a str or bytes object), or an existing file object to read from or write to.
The mode argument can be any of 'r', 'rb', 'w', 'wb', 'x', 'xb', 'a' or 'ab' for binary mode, or 'rt', 'wt', 'xt', or 'at' for text mode. The default is 'rb'.
The compresslevel argument is an integer from 1 to 9, as for the BZ2File constructor.
For binary mode, this function is equivalent to the BZ2File constructor: BZ2File(filename, mode, compresslevel=compresslevel). In this case, the encoding, errors and newline arguments must not be provided.
For text mode, a BZ2File object is created, and wrapped in an io.TextIOWrapper instance with the specified encoding, error handling behavior, and line ending(s).
New in version 3.3.
Changed in version 3.4: The 'x' (exclusive creation) mode was added.
Changed in version 3.6: Accepts a path-like object.
Open a bzip2-compressed file in binary mode.
If filename is a str or bytes object, open the named file directly. Otherwise, filename should be a file object, which will be used to read or write the compressed data.
The mode argument can be either 'r' for reading (default), 'w' for overwriting, 'x' for exclusive creation, or 'a' for appending. These can equivalently be given as 'rb', 'wb', 'xb' and 'ab' respectively.
If filename is a file object (rather than an actual file name), a mode of 'w' does not truncate the file, and is instead equivalent to 'a'.
If mode is 'w' or 'a', compresslevel can be an integer between 1 and 9 specifying the level of compression: 1 produces the least compression, and 9 (default) produces the most compression.
If mode is 'r', the input file may be the concatenation of multiple compressed streams.
BZ2File provides all of the members specified by the io.BufferedIOBase, except for detach() and truncate(). Iteration and the with statement are supported.
BZ2File also provides the following method:
Return buffered data without advancing the file position. At least one byte of data will be returned (unless at EOF). The exact number of bytes returned is unspecified.
Note
While calling peek() does not change the file position of the BZ2File, it may change the position of the underlying file object (e.g. if the BZ2File was constructed by passing a file object for filename).
New in version 3.3.
Changed in version 3.1: Support for the with statement was added.
Changed in version 3.3: The fileno(), readable(), seekable(), writable(), read1() and readinto() methods were added.
Changed in version 3.3: Support was added for filename being a file object instead of an actual filename.
Changed in version 3.3: The 'a' (append) mode was added, along with support for reading multi-stream files.
Changed in version 3.4: The 'x' (exclusive creation) mode was added.
Changed in version 3.5: The read() method now accepts an argument of None.
Changed in version 3.6: Accepts a path-like object.
Changed in version 3.9: The buffering parameter has been removed. It was ignored and deprecated since Python 3.0. Pass an open file object to control how the file is opened.
The compresslevel parameter became keyword-only.
Create a new compressor object. This object may be used to compress data incrementally. For one-shot compression, use the compress() function instead.
compresslevel, if given, must be an integer between 1 and 9. The default is 9.
Provide data to the compressor object. Returns a chunk of compressed data if possible, or an empty byte string otherwise.
When you have finished providing data to the compressor, call the flush() method to finish the compression process.
Finish the compression process. Returns the compressed data left in internal buffers.
The compressor object may not be used after this method has been called.
Create a new decompressor object. This object may be used to decompress data incrementally. For one-shot compression, use the decompress() function instead.
Note
This class does not transparently handle inputs containing multiple compressed streams, unlike decompress() and BZ2File. If you need to decompress a multi-stream input with BZ2Decompressor, you must use a new decompressor for each stream.
Decompress data (a bytes-like object), returning uncompressed data as bytes. Some of data may be buffered internally, for use in later calls to decompress(). The returned data should be concatenated with the output of any previous calls to decompress().
If max_length is nonnegative, returns at most max_length bytes of decompressed data. If this limit is reached and further output can be produced, the needs_input attribute will be set to False. In this case, the next call to decompress() may provide data as b'' to obtain more of the output.
If all of the input data was decompressed and returned (either because this was less than max_length bytes, or because max_length was negative), the needs_input attribute will be set to True.
Attempting to decompress data after the end of stream is reached raises an EOFError. Any data found after the end of the stream is ignored and saved in the unused_data attribute.
Changed in version 3.5: Added the max_length parameter.
True if the end-of-stream marker has been reached.
New in version 3.3.
Data found after the end of the compressed stream.
If this attribute is accessed before the end of the stream has been reached, its value will be b''.
False if the decompress() method can provide more decompressed data before requiring new uncompressed input.
New in version 3.5.
Compress data, a bytes-like object.
compresslevel, if given, must be an integer between 1 and 9. The default is 9.
For incremental compression, use a BZ2Compressor instead.
Decompress data, a bytes-like object.
If data is the concatenation of multiple compressed streams, decompress all of the streams.
For incremental decompression, use a BZ2Decompressor instead.
Changed in version 3.3: Support for multi-stream inputs was added.
Below are some examples of typical usage of the bz2 module.
Using compress() and decompress() to demonstrate round-trip compression:
Using BZ2Compressor for incremental compression:
The example above uses a very “nonrandom” stream of data (a stream of b”z” chunks). Random data tends to compress poorly, while ordered, repetitive data usually yields a high compression ratio.
Writing and reading a bzip2-compressed file in binary mode:


Create a new compressor object. This object may be used to compress data incrementally. For one-shot compression, use the compress() function instead.
compresslevel, if given, must be an integer between 1 and 9. The default is 9.
Provide data to the compressor object. Returns a chunk of compressed data if possible, or an empty byte string otherwise.
When you have finished providing data to the compressor, call the flush() method to finish the compression process.
Finish the compression process. Returns the compressed data left in internal buffers.
The compressor object may not be used after this method has been called.


Provide data to the compressor object. Returns a chunk of compressed data if possible, or an empty byte string otherwise.
When you have finished providing data to the compressor, call the flush() method to finish the compression process.


Finish the compression process. Returns the compressed data left in internal buffers.
The compressor object may not be used after this method has been called.


Create a new decompressor object. This object may be used to decompress data incrementally. For one-shot compression, use the decompress() function instead.
Note
This class does not transparently handle inputs containing multiple compressed streams, unlike decompress() and BZ2File. If you need to decompress a multi-stream input with BZ2Decompressor, you must use a new decompressor for each stream.
Decompress data (a bytes-like object), returning uncompressed data as bytes. Some of data may be buffered internally, for use in later calls to decompress(). The returned data should be concatenated with the output of any previous calls to decompress().
If max_length is nonnegative, returns at most max_length bytes of decompressed data. If this limit is reached and further output can be produced, the needs_input attribute will be set to False. In this case, the next call to decompress() may provide data as b'' to obtain more of the output.
If all of the input data was decompressed and returned (either because this was less than max_length bytes, or because max_length was negative), the needs_input attribute will be set to True.
Attempting to decompress data after the end of stream is reached raises an EOFError. Any data found after the end of the stream is ignored and saved in the unused_data attribute.
Changed in version 3.5: Added the max_length parameter.
True if the end-of-stream marker has been reached.
New in version 3.3.
Data found after the end of the compressed stream.
If this attribute is accessed before the end of the stream has been reached, its value will be b''.
False if the decompress() method can provide more decompressed data before requiring new uncompressed input.
New in version 3.5.


Decompress data (a bytes-like object), returning uncompressed data as bytes. Some of data may be buffered internally, for use in later calls to decompress(). The returned data should be concatenated with the output of any previous calls to decompress().
If max_length is nonnegative, returns at most max_length bytes of decompressed data. If this limit is reached and further output can be produced, the needs_input attribute will be set to False. In this case, the next call to decompress() may provide data as b'' to obtain more of the output.
If all of the input data was decompressed and returned (either because this was less than max_length bytes, or because max_length was negative), the needs_input attribute will be set to True.
Attempting to decompress data after the end of stream is reached raises an EOFError. Any data found after the end of the stream is ignored and saved in the unused_data attribute.
Changed in version 3.5: Added the max_length parameter.


True if the end-of-stream marker has been reached.
New in version 3.3.


False if the decompress() method can provide more decompressed data before requiring new uncompressed input.
New in version 3.5.


Data found after the end of the compressed stream.
If this attribute is accessed before the end of the stream has been reached, its value will be b''.


Open a bzip2-compressed file in binary mode.
If filename is a str or bytes object, open the named file directly. Otherwise, filename should be a file object, which will be used to read or write the compressed data.
The mode argument can be either 'r' for reading (default), 'w' for overwriting, 'x' for exclusive creation, or 'a' for appending. These can equivalently be given as 'rb', 'wb', 'xb' and 'ab' respectively.
If filename is a file object (rather than an actual file name), a mode of 'w' does not truncate the file, and is instead equivalent to 'a'.
If mode is 'w' or 'a', compresslevel can be an integer between 1 and 9 specifying the level of compression: 1 produces the least compression, and 9 (default) produces the most compression.
If mode is 'r', the input file may be the concatenation of multiple compressed streams.
BZ2File provides all of the members specified by the io.BufferedIOBase, except for detach() and truncate(). Iteration and the with statement are supported.
BZ2File also provides the following method:
Return buffered data without advancing the file position. At least one byte of data will be returned (unless at EOF). The exact number of bytes returned is unspecified.
Note
While calling peek() does not change the file position of the BZ2File, it may change the position of the underlying file object (e.g. if the BZ2File was constructed by passing a file object for filename).
New in version 3.3.
Changed in version 3.1: Support for the with statement was added.
Changed in version 3.3: The fileno(), readable(), seekable(), writable(), read1() and readinto() methods were added.
Changed in version 3.3: Support was added for filename being a file object instead of an actual filename.
Changed in version 3.3: The 'a' (append) mode was added, along with support for reading multi-stream files.
Changed in version 3.4: The 'x' (exclusive creation) mode was added.
Changed in version 3.5: The read() method now accepts an argument of None.
Changed in version 3.6: Accepts a path-like object.
Changed in version 3.9: The buffering parameter has been removed. It was ignored and deprecated since Python 3.0. Pass an open file object to control how the file is opened.
The compresslevel parameter became keyword-only.


Return buffered data without advancing the file position. At least one byte of data will be returned (unless at EOF). The exact number of bytes returned is unspecified.
Note
While calling peek() does not change the file position of the BZ2File, it may change the position of the underlying file object (e.g. if the BZ2File was constructed by passing a file object for filename).
New in version 3.3.


Compress data, a bytes-like object.
compresslevel, if given, must be an integer between 1 and 9. The default is 9.
For incremental compression, use a BZ2Compressor instead.


Decompress data, a bytes-like object.
If data is the concatenation of multiple compressed streams, decompress all of the streams.
For incremental decompression, use a BZ2Decompressor instead.
Changed in version 3.3: Support for multi-stream inputs was added.


Open a bzip2-compressed file in binary or text mode, returning a file object.
As with the constructor for BZ2File, the filename argument can be an actual filename (a str or bytes object), or an existing file object to read from or write to.
The mode argument can be any of 'r', 'rb', 'w', 'wb', 'x', 'xb', 'a' or 'ab' for binary mode, or 'rt', 'wt', 'xt', or 'at' for text mode. The default is 'rb'.
The compresslevel argument is an integer from 1 to 9, as for the BZ2File constructor.
For binary mode, this function is equivalent to the BZ2File constructor: BZ2File(filename, mode, compresslevel=compresslevel). In this case, the encoding, errors and newline arguments must not be provided.
For text mode, a BZ2File object is created, and wrapped in an io.TextIOWrapper instance with the specified encoding, error handling behavior, and line ending(s).
New in version 3.3.
Changed in version 3.4: The 'x' (exclusive creation) mode was added.
Changed in version 3.6: Accepts a path-like object.


Source code: Lib/calendar.py
This module allows you to output calendars like the Unix cal program, and provides additional useful functions related to the calendar. By default, these calendars have Monday as the first day of the week, and Sunday as the last (the European convention). Use setfirstweekday() to set the first day of the week to Sunday (6) or to any other weekday. Parameters that specify dates are given as integers. For related functionality, see also the datetime and time modules.
The functions and classes defined in this module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. This matches the definition of the “proleptic Gregorian” calendar in Dershowitz and Reingold’s book “Calendrical Calculations”, where it’s the base calendar for all computations. Zero and negative years are interpreted as prescribed by the ISO 8601 standard. Year 0 is 1 BC, year -1 is 2 BC, and so on.
Creates a Calendar object. firstweekday is an integer specifying the first day of the week. 0 is Monday (the default), 6 is Sunday.
A Calendar object provides several methods that can be used for preparing the calendar data for formatting. This class doesn’t do any formatting itself. This is the job of subclasses.
Calendar instances have the following methods:
Return an iterator for the week day numbers that will be used for one week. The first value from the iterator will be the same as the value of the firstweekday property.
Return an iterator for the month month (1–12) in the year year. This iterator will return all days (as datetime.date objects) for the month and all days before the start of the month or after the end of the month that are required to get a complete week.
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will simply be day of the month numbers. For the days outside of the specified month, the day number is 0.
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a day of the month number and a week day number.
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a year, a month and a day of the month numbers.
New in version 3.7.
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a year, a month, a day of the month, and a day of the week numbers.
New in version 3.7.
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven datetime.date objects.
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven tuples of day numbers and weekday numbers.
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven day numbers.
Return the data for the specified year ready for formatting. The return value is a list of month rows. Each month row contains up to width months (defaulting to 3). Each month contains between 4 and 6 weeks and each week contains 1–7 days. Days are datetime.date objects.
Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are tuples of day numbers and weekday numbers. Day numbers outside this month are zero.
Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are day numbers. Day numbers outside this month are zero.
This class can be used to generate plain text calendars.
TextCalendar instances have the following methods:
Return a month’s calendar in a multi-line string. If w is provided, it specifies the width of the date columns, which are centered. If l is given, it specifies the number of lines that each week will use. Depends on the first weekday as specified in the constructor or set by the setfirstweekday() method.
Print a month’s calendar as returned by formatmonth().
Return a m-column calendar for an entire year as a multi-line string. Optional parameters w, l, and c are for date column width, lines per week, and number of spaces between month columns, respectively. Depends on the first weekday as specified in the constructor or set by the setfirstweekday() method. The earliest year for which a calendar can be generated is platform-dependent.
Print the calendar for an entire year as returned by formatyear().
This class can be used to generate HTML calendars.
HTMLCalendar instances have the following methods:
Return a month’s calendar as an HTML table. If withyear is true the year will be included in the header, otherwise just the month name will be used.
Return a year’s calendar as an HTML table. width (defaulting to 3) specifies the number of months per row.
Return a year’s calendar as a complete HTML page. width (defaulting to 3) specifies the number of months per row. css is the name for the cascading style sheet to be used. None can be passed if no style sheet should be used. encoding specifies the encoding to be used for the output (defaulting to the system default encoding).
HTMLCalendar has the following attributes you can override to customize the CSS classes used by the calendar:
A list of CSS classes used for each weekday. The default class list is:
more styles can be added for each day:
Note that the length of this list must be seven items.
The CSS class for a weekday occurring in the previous or coming month.
New in version 3.7.
A list of CSS classes used for weekday names in the header row. The default is the same as cssclasses.
New in version 3.7.
The month’s head CSS class (used by formatmonthname()). The default value is "month".
New in version 3.7.
The CSS class for the whole month’s table (used by formatmonth()). The default value is "month".
New in version 3.7.
The CSS class for the whole year’s table of tables (used by formatyear()). The default value is "year".
New in version 3.7.
The CSS class for the table head for the whole year (used by formatyear()). The default value is "year".
New in version 3.7.
Note that although the naming for the above described class attributes is singular (e.g. cssclass_month cssclass_noday), one can replace the single CSS class with a space separated list of CSS classes, for example:
Here is an example how HTMLCalendar can be customized:
This subclass of TextCalendar can be passed a locale name in the constructor and will return month and weekday names in the specified locale. If this locale includes an encoding all strings containing month and weekday names will be returned as unicode.
This subclass of HTMLCalendar can be passed a locale name in the constructor and will return month and weekday names in the specified locale. If this locale includes an encoding all strings containing month and weekday names will be returned as unicode.
Note
The formatweekday() and formatmonthname() methods of these two classes temporarily change the current locale to the given locale. Because the current locale is a process-wide setting, they are not thread-safe.
For simple text calendars this module provides the following functions.
Sets the weekday (0 is Monday, 6 is Sunday) to start each week. The values MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY are provided for convenience. For example, to set the first weekday to Sunday:
Returns the current setting for the weekday to start each week.
Returns True if year is a leap year, otherwise False.
Returns the number of leap years in the range from y1 to y2 (exclusive), where y1 and y2 are years.
This function works for ranges spanning a century change.
Returns the day of the week (0 is Monday) for year (1970–…), month (1–12), day (1–31).
Return a header containing abbreviated weekday names. n specifies the width in characters for one weekday.
Returns weekday of first day of the month and number of days in month, for the specified year and month.
Returns a matrix representing a month’s calendar. Each row represents a week; days outside of the month are represented by zeros. Each week begins with Monday unless set by setfirstweekday().
Prints a month’s calendar as returned by month().
Returns a month’s calendar in a multi-line string using the formatmonth() of the TextCalendar class.
Prints the calendar for an entire year as returned by calendar().
Returns a 3-column calendar for an entire year as a multi-line string using the formatyear() of the TextCalendar class.
An unrelated but handy function that takes a time tuple such as returned by the gmtime() function in the time module, and returns the corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX encoding. In fact, time.gmtime() and timegm() are each others’ inverse.
The calendar module exports the following data attributes:
An array that represents the days of the week in the current locale.
An array that represents the abbreviated days of the week in the current locale.
An array that represents the months of the year in the current locale. This follows normal convention of January being month number 1, so it has a length of 13 and month_name[0] is the empty string.
An array that represents the abbreviated months of the year in the current locale. This follows normal convention of January being month number 1, so it has a length of 13 and month_abbr[0] is the empty string.
See also
Object-oriented interface to dates and times with similar functionality to the time module.
Low-level time related functions.


Creates a Calendar object. firstweekday is an integer specifying the first day of the week. 0 is Monday (the default), 6 is Sunday.
A Calendar object provides several methods that can be used for preparing the calendar data for formatting. This class doesn’t do any formatting itself. This is the job of subclasses.
Calendar instances have the following methods:
Return an iterator for the week day numbers that will be used for one week. The first value from the iterator will be the same as the value of the firstweekday property.
Return an iterator for the month month (1–12) in the year year. This iterator will return all days (as datetime.date objects) for the month and all days before the start of the month or after the end of the month that are required to get a complete week.
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will simply be day of the month numbers. For the days outside of the specified month, the day number is 0.
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a day of the month number and a week day number.
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a year, a month and a day of the month numbers.
New in version 3.7.
Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a year, a month, a day of the month, and a day of the week numbers.
New in version 3.7.
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven datetime.date objects.
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven tuples of day numbers and weekday numbers.
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven day numbers.
Return the data for the specified year ready for formatting. The return value is a list of month rows. Each month row contains up to width months (defaulting to 3). Each month contains between 4 and 6 weeks and each week contains 1–7 days. Days are datetime.date objects.
Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are tuples of day numbers and weekday numbers. Day numbers outside this month are zero.
Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are day numbers. Day numbers outside this month are zero.


Returns a 3-column calendar for an entire year as a multi-line string using the formatyear() of the TextCalendar class.


Return an iterator for the month month (1–12) in the year year. This iterator will return all days (as datetime.date objects) for the month and all days before the start of the month or after the end of the month that are required to get a complete week.


Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will simply be day of the month numbers. For the days outside of the specified month, the day number is 0.


Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a day of the month number and a week day number.


Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a year, a month and a day of the month numbers.
New in version 3.7.


Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a year, a month, a day of the month, and a day of the week numbers.
New in version 3.7.


Return an iterator for the week day numbers that will be used for one week. The first value from the iterator will be the same as the value of the firstweekday property.


Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven datetime.date objects.


Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven tuples of day numbers and weekday numbers.


Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven day numbers.


Return the data for the specified year ready for formatting. The return value is a list of month rows. Each month row contains up to width months (defaulting to 3). Each month contains between 4 and 6 weeks and each week contains 1–7 days. Days are datetime.date objects.


Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are tuples of day numbers and weekday numbers. Day numbers outside this month are zero.


Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are day numbers. Day numbers outside this month are zero.


An array that represents the abbreviated days of the week in the current locale.


An array that represents the days of the week in the current locale.


Returns the current setting for the weekday to start each week.


This class can be used to generate HTML calendars.
HTMLCalendar instances have the following methods:
Return a month’s calendar as an HTML table. If withyear is true the year will be included in the header, otherwise just the month name will be used.
Return a year’s calendar as an HTML table. width (defaulting to 3) specifies the number of months per row.
Return a year’s calendar as a complete HTML page. width (defaulting to 3) specifies the number of months per row. css is the name for the cascading style sheet to be used. None can be passed if no style sheet should be used. encoding specifies the encoding to be used for the output (defaulting to the system default encoding).
HTMLCalendar has the following attributes you can override to customize the CSS classes used by the calendar:
A list of CSS classes used for each weekday. The default class list is:
more styles can be added for each day:
Note that the length of this list must be seven items.
The CSS class for a weekday occurring in the previous or coming month.
New in version 3.7.
A list of CSS classes used for weekday names in the header row. The default is the same as cssclasses.
New in version 3.7.
The month’s head CSS class (used by formatmonthname()). The default value is "month".
New in version 3.7.
The CSS class for the whole month’s table (used by formatmonth()). The default value is "month".
New in version 3.7.
The CSS class for the whole year’s table of tables (used by formatyear()). The default value is "year".
New in version 3.7.
The CSS class for the table head for the whole year (used by formatyear()). The default value is "year".
New in version 3.7.
Note that although the naming for the above described class attributes is singular (e.g. cssclass_month cssclass_noday), one can replace the single CSS class with a space separated list of CSS classes, for example:
Here is an example how HTMLCalendar can be customized:


A list of CSS classes used for each weekday. The default class list is:
more styles can be added for each day:
Note that the length of this list must be seven items.


A list of CSS classes used for weekday names in the header row. The default is the same as cssclasses.
New in version 3.7.


The CSS class for the whole month’s table (used by formatmonth()). The default value is "month".
New in version 3.7.


The month’s head CSS class (used by formatmonthname()). The default value is "month".
New in version 3.7.


The CSS class for a weekday occurring in the previous or coming month.
New in version 3.7.


The CSS class for the whole year’s table of tables (used by formatyear()). The default value is "year".
New in version 3.7.


The CSS class for the table head for the whole year (used by formatyear()). The default value is "year".
New in version 3.7.


Return a month’s calendar as an HTML table. If withyear is true the year will be included in the header, otherwise just the month name will be used.


Return a year’s calendar as an HTML table. width (defaulting to 3) specifies the number of months per row.


Return a year’s calendar as a complete HTML page. width (defaulting to 3) specifies the number of months per row. css is the name for the cascading style sheet to be used. None can be passed if no style sheet should be used. encoding specifies the encoding to be used for the output (defaulting to the system default encoding).


Returns True if year is a leap year, otherwise False.


Returns the number of leap years in the range from y1 to y2 (exclusive), where y1 and y2 are years.
This function works for ranges spanning a century change.


This subclass of HTMLCalendar can be passed a locale name in the constructor and will return month and weekday names in the specified locale. If this locale includes an encoding all strings containing month and weekday names will be returned as unicode.


This subclass of TextCalendar can be passed a locale name in the constructor and will return month and weekday names in the specified locale. If this locale includes an encoding all strings containing month and weekday names will be returned as unicode.


Returns a month’s calendar in a multi-line string using the formatmonth() of the TextCalendar class.


Returns a matrix representing a month’s calendar. Each row represents a week; days outside of the month are represented by zeros. Each week begins with Monday unless set by setfirstweekday().


Returns weekday of first day of the month and number of days in month, for the specified year and month.


An array that represents the abbreviated months of the year in the current locale. This follows normal convention of January being month number 1, so it has a length of 13 and month_abbr[0] is the empty string.


An array that represents the months of the year in the current locale. This follows normal convention of January being month number 1, so it has a length of 13 and month_name[0] is the empty string.


Prints the calendar for an entire year as returned by calendar().


Prints a month’s calendar as returned by month().


Sets the weekday (0 is Monday, 6 is Sunday) to start each week. The values MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY are provided for convenience. For example, to set the first weekday to Sunday:


This class can be used to generate plain text calendars.
TextCalendar instances have the following methods:
Return a month’s calendar in a multi-line string. If w is provided, it specifies the width of the date columns, which are centered. If l is given, it specifies the number of lines that each week will use. Depends on the first weekday as specified in the constructor or set by the setfirstweekday() method.
Print a month’s calendar as returned by formatmonth().
Return a m-column calendar for an entire year as a multi-line string. Optional parameters w, l, and c are for date column width, lines per week, and number of spaces between month columns, respectively. Depends on the first weekday as specified in the constructor or set by the setfirstweekday() method. The earliest year for which a calendar can be generated is platform-dependent.
Print the calendar for an entire year as returned by formatyear().


Return a month’s calendar in a multi-line string. If w is provided, it specifies the width of the date columns, which are centered. If l is given, it specifies the number of lines that each week will use. Depends on the first weekday as specified in the constructor or set by the setfirstweekday() method.


Return a m-column calendar for an entire year as a multi-line string. Optional parameters w, l, and c are for date column width, lines per week, and number of spaces between month columns, respectively. Depends on the first weekday as specified in the constructor or set by the setfirstweekday() method. The earliest year for which a calendar can be generated is platform-dependent.


Print a month’s calendar as returned by formatmonth().


Print the calendar for an entire year as returned by formatyear().


An unrelated but handy function that takes a time tuple such as returned by the gmtime() function in the time module, and returns the corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX encoding. In fact, time.gmtime() and timegm() are each others’ inverse.


Returns the day of the week (0 is Monday) for year (1970–…), month (1–12), day (1–31).


Return a header containing abbreviated weekday names. n specifies the width in characters for one weekday.


Return True if the object argument appears callable, False if not. If this returns True, it is still possible that a call fails, but if it is False, 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.
New in version 3.2: This function was first removed in Python 3.0 and then brought back in Python 3.2.