doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
bytes.isalpha()
bytearray.isalpha()
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: >>> b'ABCabc'.isalpha()
True
>>> b'ABCabc1'.isalpha()
False | python.library.stdtypes#bytearray.isalpha |
bytes.isascii()
bytearray.isascii()
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. | python.library.stdtypes#bytearray.isascii |
bytes.isdigit()
bytearray.isdigit()
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: >>> b'1234'.isdigit()
True
>>> b'1.23'.isdigit()
False | python.library.stdtypes#bytearray.isdigit |
bytes.islower()
bytearray.islower()
Return True if there is at least one lowercase ASCII character in the sequence and no uppercase ASCII characters, False otherwise. For example: >>> b'hello world'.islower()
True
>>> b'Hello world'.islower()
False
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. | python.library.stdtypes#bytearray.islower |
bytes.isspace()
bytearray.isspace()
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). | python.library.stdtypes#bytearray.isspace |
bytes.istitle()
bytearray.istitle()
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: >>> b'Hello World'.istitle()
True
>>> b'Hello world'.istitle()
False | python.library.stdtypes#bytearray.istitle |
bytes.isupper()
bytearray.isupper()
Return True if there is at least one uppercase alphabetic ASCII character in the sequence and no lowercase ASCII characters, False otherwise. For example: >>> b'HELLO WORLD'.isupper()
True
>>> b'Hello world'.isupper()
False
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. | python.library.stdtypes#bytearray.isupper |
bytes.join(iterable)
bytearray.join(iterable)
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. | python.library.stdtypes#bytearray.join |
bytes.ljust(width[, fillbyte])
bytearray.ljust(width[, fillbyte])
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. | python.library.stdtypes#bytearray.ljust |
bytes.lower()
bytearray.lower()
Return a copy of the sequence with all the uppercase ASCII characters converted to their corresponding lowercase counterpart. For example: >>> b'Hello World'.lower()
b'hello world'
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. | python.library.stdtypes#bytearray.lower |
bytes.lstrip([chars])
bytearray.lstrip([chars])
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: >>> b' spacious '.lstrip()
b'spacious '
>>> b'www.example.com'.lstrip(b'cmowz.')
b'example.com'
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: >>> b'Arthur: three!'.lstrip(b'Arthur: ')
b'ee!'
>>> b'Arthur: three!'.removeprefix(b'Arthur: ')
b'three!'
Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made. | python.library.stdtypes#bytearray.lstrip |
static bytes.maketrans(from, to)
static bytearray.maketrans(from, to)
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. | python.library.stdtypes#bytearray.maketrans |
bytes.partition(sep)
bytearray.partition(sep)
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. | python.library.stdtypes#bytearray.partition |
bytes.removeprefix(prefix, /)
bytearray.removeprefix(prefix, /)
If the binary data starts with the prefix string, return bytes[len(prefix):]. Otherwise, return a copy of the original binary data: >>> b'TestHook'.removeprefix(b'Test')
b'Hook'
>>> b'BaseTestCase'.removeprefix(b'Test')
b'BaseTestCase'
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. | python.library.stdtypes#bytearray.removeprefix |
bytes.removesuffix(suffix, /)
bytearray.removesuffix(suffix, /)
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: >>> b'MiscTests'.removesuffix(b'Tests')
b'Misc'
>>> b'TmpDirMixin'.removesuffix(b'Tests')
b'TmpDirMixin'
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. | python.library.stdtypes#bytearray.removesuffix |
bytes.replace(old, new[, count])
bytearray.replace(old, new[, count])
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. | python.library.stdtypes#bytearray.replace |
bytes.rfind(sub[, start[, end]])
bytearray.rfind(sub[, start[, end]])
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. | python.library.stdtypes#bytearray.rfind |
bytes.rindex(sub[, start[, end]])
bytearray.rindex(sub[, start[, end]])
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. | python.library.stdtypes#bytearray.rindex |
bytes.rjust(width[, fillbyte])
bytearray.rjust(width[, fillbyte])
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. | python.library.stdtypes#bytearray.rjust |
bytes.rpartition(sep)
bytearray.rpartition(sep)
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. | python.library.stdtypes#bytearray.rpartition |
bytes.rsplit(sep=None, maxsplit=-1)
bytearray.rsplit(sep=None, maxsplit=-1)
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. | python.library.stdtypes#bytearray.rsplit |
bytes.rstrip([chars])
bytearray.rstrip([chars])
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: >>> b' spacious '.rstrip()
b' spacious'
>>> b'mississippi'.rstrip(b'ipz')
b'mississ'
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: >>> b'Monty Python'.rstrip(b' Python')
b'M'
>>> b'Monty Python'.removesuffix(b' Python')
b'Monty'
Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made. | python.library.stdtypes#bytearray.rstrip |
bytes.split(sep=None, maxsplit=-1)
bytearray.split(sep=None, maxsplit=-1)
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: >>> b'1,2,3'.split(b',')
[b'1', b'2', b'3']
>>> b'1,2,3'.split(b',', maxsplit=1)
[b'1', b'2,3']
>>> b'1,2,,3,'.split(b',')
[b'1', b'2', b'', b'3', b'']
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: >>> b'1 2 3'.split()
[b'1', b'2', b'3']
>>> b'1 2 3'.split(maxsplit=1)
[b'1', b'2 3']
>>> b' 1 2 3 '.split()
[b'1', b'2', b'3'] | python.library.stdtypes#bytearray.split |
bytes.splitlines(keepends=False)
bytearray.splitlines(keepends=False)
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: >>> b'ab c\n\nde fg\rkl\r\n'.splitlines()
[b'ab c', b'', b'de fg', b'kl']
>>> b'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
[b'ab c\n', b'\n', b'de fg\r', b'kl\r\n']
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: >>> b"".split(b'\n'), b"Two lines\n".split(b'\n')
([b''], [b'Two lines', b''])
>>> b"".splitlines(), b"One line\n".splitlines()
([], [b'One line']) | python.library.stdtypes#bytearray.splitlines |
bytes.startswith(prefix[, start[, end]])
bytearray.startswith(prefix[, start[, end]])
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. | python.library.stdtypes#bytearray.startswith |
bytes.strip([chars])
bytearray.strip([chars])
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: >>> b' spacious '.strip()
b'spacious'
>>> b'www.example.com'.strip(b'cmowz.')
b'example'
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. | python.library.stdtypes#bytearray.strip |
bytes.swapcase()
bytearray.swapcase()
Return a copy of the sequence with all the lowercase ASCII characters converted to their corresponding uppercase counterpart and vice-versa. For example: >>> b'Hello World'.swapcase()
b'hELLO wORLD'
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. | python.library.stdtypes#bytearray.swapcase |
bytes.title()
bytearray.title()
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: >>> b'Hello world'.title()
b'Hello World'
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: >>> b"they're bill's friends from the UK".title()
b"They'Re Bill'S Friends From The Uk"
A workaround for apostrophes can be constructed using regular expressions: >>> import re
>>> def titlecase(s):
... return re.sub(rb"[A-Za-z]+('[A-Za-z]+)?",
... lambda mo: mo.group(0)[0:1].upper() +
... mo.group(0)[1:].lower(),
... s)
...
>>> titlecase(b"they're bill's friends.")
b"They're Bill's Friends."
Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made. | python.library.stdtypes#bytearray.title |
bytes.translate(table, /, delete=b'')
bytearray.translate(table, /, delete=b'')
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: >>> b'read this short text'.translate(None, b'aeiou')
b'rd ths shrt txt'
Changed in version 3.6: delete is now supported as a keyword argument. | python.library.stdtypes#bytearray.translate |
bytes.upper()
bytearray.upper()
Return a copy of the sequence with all the lowercase ASCII characters converted to their corresponding uppercase counterpart. For example: >>> b'Hello World'.upper()
b'HELLO WORLD'
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. | python.library.stdtypes#bytearray.upper |
bytes.zfill(width)
bytearray.zfill(width)
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: >>> b"42".zfill(5)
b'00042'
>>> b"-42".zfill(5)
b'-0042'
Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made. | python.library.stdtypes#bytearray.zfill |
class bytes([source[, encoding[, errors]]])
Firstly, the syntax for bytes literals is largely the same as that for string literals, except that a b prefix is added: Single quotes: b'still allows embedded "double" quotes'
Double quotes: b"still allows embedded 'single' quotes". Triple quoted: b'''3 single quotes''', b"""3 double quotes"""
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: A zero-filled bytes object of a specified length: bytes(10)
From an iterable of integers: bytes(range(20))
Copying existing binary data via the buffer protocol: bytes(obj)
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:
classmethod fromhex(string)
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. >>> bytes.fromhex('2Ef0 F1f2 ')
b'.\xf0\xf1\xf2'
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.
hex([sep[, bytes_per_sep]])
Return a string object containing two hexadecimal digits for each byte in the instance. >>> b'\xf0\xf1\xf2'.hex()
'f0f1f2'
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. >>> value = b'\xf0\xf1\xf2'
>>> value.hex('-')
'f0-f1-f2'
>>> value.hex('_', 2)
'f0_f1f2'
>>> b'UUDDLRLRAB'.hex(' ', -4)
'55554444 4c524c52 4142'
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. | python.library.stdtypes#bytes |
class bytes([source[, encoding[, errors]]])
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. | python.library.functions#bytes |
bytes.capitalize()
bytearray.capitalize()
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. | python.library.stdtypes#bytes.capitalize |
bytes.center(width[, fillbyte])
bytearray.center(width[, fillbyte])
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. | python.library.stdtypes#bytes.center |
bytes.count(sub[, start[, end]])
bytearray.count(sub[, start[, end]])
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. | python.library.stdtypes#bytes.count |
bytes.decode(encoding="utf-8", errors="strict")
bytearray.decode(encoding="utf-8", errors="strict")
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. | python.library.stdtypes#bytes.decode |
bytes.endswith(suffix[, start[, end]])
bytearray.endswith(suffix[, start[, end]])
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. | python.library.stdtypes#bytes.endswith |
bytes.expandtabs(tabsize=8)
bytearray.expandtabs(tabsize=8)
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: >>> b'01\t012\t0123\t01234'.expandtabs()
b'01 012 0123 01234'
>>> b'01\t012\t0123\t01234'.expandtabs(4)
b'01 012 0123 01234'
Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made. | python.library.stdtypes#bytes.expandtabs |
bytes.find(sub[, start[, end]])
bytearray.find(sub[, start[, end]])
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: >>> b'Py' in b'Python'
True
Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence. | python.library.stdtypes#bytes.find |
classmethod fromhex(string)
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. >>> bytes.fromhex('2Ef0 F1f2 ')
b'.\xf0\xf1\xf2'
Changed in version 3.7: bytes.fromhex() now skips all ASCII whitespace in the string, not just spaces. | python.library.stdtypes#bytes.fromhex |
hex([sep[, bytes_per_sep]])
Return a string object containing two hexadecimal digits for each byte in the instance. >>> b'\xf0\xf1\xf2'.hex()
'f0f1f2'
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. >>> value = b'\xf0\xf1\xf2'
>>> value.hex('-')
'f0-f1-f2'
>>> value.hex('_', 2)
'f0_f1f2'
>>> b'UUDDLRLRAB'.hex(' ', -4)
'55554444 4c524c52 4142'
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. | python.library.stdtypes#bytes.hex |
bytes.index(sub[, start[, end]])
bytearray.index(sub[, start[, end]])
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. | python.library.stdtypes#bytes.index |
bytes.isalnum()
bytearray.isalnum()
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: >>> b'ABCabc1'.isalnum()
True
>>> b'ABC abc1'.isalnum()
False | python.library.stdtypes#bytes.isalnum |
bytes.isalpha()
bytearray.isalpha()
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: >>> b'ABCabc'.isalpha()
True
>>> b'ABCabc1'.isalpha()
False | python.library.stdtypes#bytes.isalpha |
bytes.isascii()
bytearray.isascii()
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. | python.library.stdtypes#bytes.isascii |
bytes.isdigit()
bytearray.isdigit()
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: >>> b'1234'.isdigit()
True
>>> b'1.23'.isdigit()
False | python.library.stdtypes#bytes.isdigit |
bytes.islower()
bytearray.islower()
Return True if there is at least one lowercase ASCII character in the sequence and no uppercase ASCII characters, False otherwise. For example: >>> b'hello world'.islower()
True
>>> b'Hello world'.islower()
False
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. | python.library.stdtypes#bytes.islower |
bytes.isspace()
bytearray.isspace()
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). | python.library.stdtypes#bytes.isspace |
bytes.istitle()
bytearray.istitle()
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: >>> b'Hello World'.istitle()
True
>>> b'Hello world'.istitle()
False | python.library.stdtypes#bytes.istitle |
bytes.isupper()
bytearray.isupper()
Return True if there is at least one uppercase alphabetic ASCII character in the sequence and no lowercase ASCII characters, False otherwise. For example: >>> b'HELLO WORLD'.isupper()
True
>>> b'Hello world'.isupper()
False
Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. | python.library.stdtypes#bytes.isupper |
bytes.join(iterable)
bytearray.join(iterable)
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. | python.library.stdtypes#bytes.join |
bytes.ljust(width[, fillbyte])
bytearray.ljust(width[, fillbyte])
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. | python.library.stdtypes#bytes.ljust |
bytes.lower()
bytearray.lower()
Return a copy of the sequence with all the uppercase ASCII characters converted to their corresponding lowercase counterpart. For example: >>> b'Hello World'.lower()
b'hello world'
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. | python.library.stdtypes#bytes.lower |
bytes.lstrip([chars])
bytearray.lstrip([chars])
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: >>> b' spacious '.lstrip()
b'spacious '
>>> b'www.example.com'.lstrip(b'cmowz.')
b'example.com'
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: >>> b'Arthur: three!'.lstrip(b'Arthur: ')
b'ee!'
>>> b'Arthur: three!'.removeprefix(b'Arthur: ')
b'three!'
Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made. | python.library.stdtypes#bytes.lstrip |
static bytes.maketrans(from, to)
static bytearray.maketrans(from, to)
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. | python.library.stdtypes#bytes.maketrans |
bytes.partition(sep)
bytearray.partition(sep)
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. | python.library.stdtypes#bytes.partition |
bytes.removeprefix(prefix, /)
bytearray.removeprefix(prefix, /)
If the binary data starts with the prefix string, return bytes[len(prefix):]. Otherwise, return a copy of the original binary data: >>> b'TestHook'.removeprefix(b'Test')
b'Hook'
>>> b'BaseTestCase'.removeprefix(b'Test')
b'BaseTestCase'
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. | python.library.stdtypes#bytes.removeprefix |
bytes.removesuffix(suffix, /)
bytearray.removesuffix(suffix, /)
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: >>> b'MiscTests'.removesuffix(b'Tests')
b'Misc'
>>> b'TmpDirMixin'.removesuffix(b'Tests')
b'TmpDirMixin'
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. | python.library.stdtypes#bytes.removesuffix |
bytes.replace(old, new[, count])
bytearray.replace(old, new[, count])
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. | python.library.stdtypes#bytes.replace |
bytes.rfind(sub[, start[, end]])
bytearray.rfind(sub[, start[, end]])
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. | python.library.stdtypes#bytes.rfind |
bytes.rindex(sub[, start[, end]])
bytearray.rindex(sub[, start[, end]])
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. | python.library.stdtypes#bytes.rindex |
bytes.rjust(width[, fillbyte])
bytearray.rjust(width[, fillbyte])
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. | python.library.stdtypes#bytes.rjust |
bytes.rpartition(sep)
bytearray.rpartition(sep)
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. | python.library.stdtypes#bytes.rpartition |
bytes.rsplit(sep=None, maxsplit=-1)
bytearray.rsplit(sep=None, maxsplit=-1)
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. | python.library.stdtypes#bytes.rsplit |
bytes.rstrip([chars])
bytearray.rstrip([chars])
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: >>> b' spacious '.rstrip()
b' spacious'
>>> b'mississippi'.rstrip(b'ipz')
b'mississ'
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: >>> b'Monty Python'.rstrip(b' Python')
b'M'
>>> b'Monty Python'.removesuffix(b' Python')
b'Monty'
Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made. | python.library.stdtypes#bytes.rstrip |
bytes.split(sep=None, maxsplit=-1)
bytearray.split(sep=None, maxsplit=-1)
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: >>> b'1,2,3'.split(b',')
[b'1', b'2', b'3']
>>> b'1,2,3'.split(b',', maxsplit=1)
[b'1', b'2,3']
>>> b'1,2,,3,'.split(b',')
[b'1', b'2', b'', b'3', b'']
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: >>> b'1 2 3'.split()
[b'1', b'2', b'3']
>>> b'1 2 3'.split(maxsplit=1)
[b'1', b'2 3']
>>> b' 1 2 3 '.split()
[b'1', b'2', b'3'] | python.library.stdtypes#bytes.split |
bytes.splitlines(keepends=False)
bytearray.splitlines(keepends=False)
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: >>> b'ab c\n\nde fg\rkl\r\n'.splitlines()
[b'ab c', b'', b'de fg', b'kl']
>>> b'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
[b'ab c\n', b'\n', b'de fg\r', b'kl\r\n']
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: >>> b"".split(b'\n'), b"Two lines\n".split(b'\n')
([b''], [b'Two lines', b''])
>>> b"".splitlines(), b"One line\n".splitlines()
([], [b'One line']) | python.library.stdtypes#bytes.splitlines |
bytes.startswith(prefix[, start[, end]])
bytearray.startswith(prefix[, start[, end]])
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. | python.library.stdtypes#bytes.startswith |
bytes.strip([chars])
bytearray.strip([chars])
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: >>> b' spacious '.strip()
b'spacious'
>>> b'www.example.com'.strip(b'cmowz.')
b'example'
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. | python.library.stdtypes#bytes.strip |
bytes.swapcase()
bytearray.swapcase()
Return a copy of the sequence with all the lowercase ASCII characters converted to their corresponding uppercase counterpart and vice-versa. For example: >>> b'Hello World'.swapcase()
b'hELLO wORLD'
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. | python.library.stdtypes#bytes.swapcase |
bytes.title()
bytearray.title()
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: >>> b'Hello world'.title()
b'Hello World'
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: >>> b"they're bill's friends from the UK".title()
b"They'Re Bill'S Friends From The Uk"
A workaround for apostrophes can be constructed using regular expressions: >>> import re
>>> def titlecase(s):
... return re.sub(rb"[A-Za-z]+('[A-Za-z]+)?",
... lambda mo: mo.group(0)[0:1].upper() +
... mo.group(0)[1:].lower(),
... s)
...
>>> titlecase(b"they're bill's friends.")
b"They're Bill's Friends."
Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made. | python.library.stdtypes#bytes.title |
bytes.translate(table, /, delete=b'')
bytearray.translate(table, /, delete=b'')
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: >>> b'read this short text'.translate(None, b'aeiou')
b'rd ths shrt txt'
Changed in version 3.6: delete is now supported as a keyword argument. | python.library.stdtypes#bytes.translate |
bytes.upper()
bytearray.upper()
Return a copy of the sequence with all the lowercase ASCII characters converted to their corresponding uppercase counterpart. For example: >>> b'Hello World'.upper()
b'HELLO WORLD'
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. | python.library.stdtypes#bytes.upper |
bytes.zfill(width)
bytearray.zfill(width)
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: >>> b"42".zfill(5)
b'00042'
>>> b"-42".zfill(5)
b'-0042'
Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made. | python.library.stdtypes#bytes.zfill |
exception BytesWarning
Base class for warnings related to bytes and bytearray. | python.library.exceptions#BytesWarning |
bz2 — Support for bzip2 compression 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: The open() function and BZ2File class for reading and writing compressed files. The BZ2Compressor and BZ2Decompressor classes for incremental (de)compression. The compress() and decompress() functions for one-shot (de)compression. All of the classes in this module may safely be accessed from multiple threads. (De)compression of files
bz2.open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None)
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.
class bz2.BZ2File(filename, mode='r', *, compresslevel=9)
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:
peek([n])
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.
Incremental (de)compression
class bz2.BZ2Compressor(compresslevel=9)
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.
compress(data)
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.
flush()
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.
class bz2.BZ2Decompressor
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, max_length=-1)
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.
eof
True if the end-of-stream marker has been reached. New in version 3.3.
unused_data
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''.
needs_input
False if the decompress() method can provide more decompressed data before requiring new uncompressed input. New in version 3.5.
One-shot (de)compression
bz2.compress(data, compresslevel=9)
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.
bz2.decompress(data)
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.
Examples of usage Below are some examples of typical usage of the bz2 module. Using compress() and decompress() to demonstrate round-trip compression: >>> import bz2
>>> data = b"""\
... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus
... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat.
... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""
>>> c = bz2.compress(data)
>>> len(data) / len(c) # Data compression ratio
1.513595166163142
>>> d = bz2.decompress(c)
>>> data == d # Check equality to original object after round-trip
True
Using BZ2Compressor for incremental compression: >>> import bz2
>>> def gen_data(chunks=10, chunksize=1000):
... """Yield incremental blocks of chunksize bytes."""
... for _ in range(chunks):
... yield b"z" * chunksize
...
>>> comp = bz2.BZ2Compressor()
>>> out = b""
>>> for chunk in gen_data():
... # Provide data to the compressor object
... out = out + comp.compress(chunk)
...
>>> # Finish the compression process. Call this once you have
>>> # finished providing data to the compressor.
>>> out = out + comp.flush()
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: >>> import bz2
>>> data = b"""\
... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus
... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat.
... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""
>>> with bz2.open("myfile.bz2", "wb") as f:
... # Write compressed data to file
... unused = f.write(data)
>>> with bz2.open("myfile.bz2", "rb") as f:
... # Decompress data from file
... content = f.read()
>>> content == data # Check equality to original object after round-trip
True | python.library.bz2 |
class bz2.BZ2Compressor(compresslevel=9)
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.
compress(data)
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.
flush()
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. | python.library.bz2#bz2.BZ2Compressor |
compress(data)
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. | python.library.bz2#bz2.BZ2Compressor.compress |
flush()
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. | python.library.bz2#bz2.BZ2Compressor.flush |
class bz2.BZ2Decompressor
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, max_length=-1)
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.
eof
True if the end-of-stream marker has been reached. New in version 3.3.
unused_data
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''.
needs_input
False if the decompress() method can provide more decompressed data before requiring new uncompressed input. New in version 3.5. | python.library.bz2#bz2.BZ2Decompressor |
decompress(data, max_length=-1)
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. | python.library.bz2#bz2.BZ2Decompressor.decompress |
eof
True if the end-of-stream marker has been reached. New in version 3.3. | python.library.bz2#bz2.BZ2Decompressor.eof |
needs_input
False if the decompress() method can provide more decompressed data before requiring new uncompressed input. New in version 3.5. | python.library.bz2#bz2.BZ2Decompressor.needs_input |
unused_data
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''. | python.library.bz2#bz2.BZ2Decompressor.unused_data |
class bz2.BZ2File(filename, mode='r', *, compresslevel=9)
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:
peek([n])
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. | python.library.bz2#bz2.BZ2File |
peek([n])
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. | python.library.bz2#bz2.BZ2File.peek |
bz2.compress(data, compresslevel=9)
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. | python.library.bz2#bz2.compress |
bz2.decompress(data)
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. | python.library.bz2#bz2.decompress |
bz2.open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None)
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. | python.library.bz2#bz2.open |
calendar — General calendar-related functions 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.
class calendar.Calendar(firstweekday=0)
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:
iterweekdays()
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.
itermonthdates(year, month)
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.
itermonthdays(year, month)
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.
itermonthdays2(year, month)
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.
itermonthdays3(year, month)
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.
itermonthdays4(year, month)
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.
monthdatescalendar(year, month)
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven datetime.date objects.
monthdays2calendar(year, month)
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.
monthdayscalendar(year, month)
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven day numbers.
yeardatescalendar(year, width=3)
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.
yeardays2calendar(year, width=3)
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.
yeardayscalendar(year, width=3)
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.
class calendar.TextCalendar(firstweekday=0)
This class can be used to generate plain text calendars. TextCalendar instances have the following methods:
formatmonth(theyear, themonth, w=0, l=0)
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.
prmonth(theyear, themonth, w=0, l=0)
Print a month’s calendar as returned by formatmonth().
formatyear(theyear, w=2, l=1, c=6, m=3)
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.
pryear(theyear, w=2, l=1, c=6, m=3)
Print the calendar for an entire year as returned by formatyear().
class calendar.HTMLCalendar(firstweekday=0)
This class can be used to generate HTML calendars. HTMLCalendar instances have the following methods:
formatmonth(theyear, themonth, withyear=True)
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.
formatyear(theyear, width=3)
Return a year’s calendar as an HTML table. width (defaulting to 3) specifies the number of months per row.
formatyearpage(theyear, width=3, css='calendar.css', encoding=None)
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:
cssclasses
A list of CSS classes used for each weekday. The default class list is: cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
more styles can be added for each day: cssclasses = ["mon text-bold", "tue", "wed", "thu", "fri", "sat", "sun red"]
Note that the length of this list must be seven items.
cssclass_noday
The CSS class for a weekday occurring in the previous or coming month. New in version 3.7.
cssclasses_weekday_head
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.
cssclass_month_head
The month’s head CSS class (used by formatmonthname()). The default value is "month". New in version 3.7.
cssclass_month
The CSS class for the whole month’s table (used by formatmonth()). The default value is "month". New in version 3.7.
cssclass_year
The CSS class for the whole year’s table of tables (used by formatyear()). The default value is "year". New in version 3.7.
cssclass_year_head
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: "text-bold text-red"
Here is an example how HTMLCalendar can be customized: class CustomHTMLCal(calendar.HTMLCalendar):
cssclasses = [style + " text-nowrap" for style in
calendar.HTMLCalendar.cssclasses]
cssclass_month_head = "text-center month-head"
cssclass_month = "text-center month"
cssclass_year = "text-italic lead"
class calendar.LocaleTextCalendar(firstweekday=0, locale=None)
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.
class calendar.LocaleHTMLCalendar(firstweekday=0, locale=None)
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.
calendar.setfirstweekday(weekday)
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: import calendar
calendar.setfirstweekday(calendar.SUNDAY)
calendar.firstweekday()
Returns the current setting for the weekday to start each week.
calendar.isleap(year)
Returns True if year is a leap year, otherwise False.
calendar.leapdays(y1, y2)
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.
calendar.weekday(year, month, day)
Returns the day of the week (0 is Monday) for year (1970–…), month (1–12), day (1–31).
calendar.weekheader(n)
Return a header containing abbreviated weekday names. n specifies the width in characters for one weekday.
calendar.monthrange(year, month)
Returns weekday of first day of the month and number of days in month, for the specified year and month.
calendar.monthcalendar(year, 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().
calendar.prmonth(theyear, themonth, w=0, l=0)
Prints a month’s calendar as returned by month().
calendar.month(theyear, themonth, w=0, l=0)
Returns a month’s calendar in a multi-line string using the formatmonth() of the TextCalendar class.
calendar.prcal(year, w=0, l=0, c=6, m=3)
Prints the calendar for an entire year as returned by calendar().
calendar.calendar(year, w=2, l=1, c=6, m=3)
Returns a 3-column calendar for an entire year as a multi-line string using the formatyear() of the TextCalendar class.
calendar.timegm(tuple)
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:
calendar.day_name
An array that represents the days of the week in the current locale.
calendar.day_abbr
An array that represents the abbreviated days of the week in the current locale.
calendar.month_name
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.
calendar.month_abbr
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
Module datetime
Object-oriented interface to dates and times with similar functionality to the time module.
Module time
Low-level time related functions. | python.library.calendar |
class calendar.Calendar(firstweekday=0)
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:
iterweekdays()
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.
itermonthdates(year, month)
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.
itermonthdays(year, month)
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.
itermonthdays2(year, month)
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.
itermonthdays3(year, month)
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.
itermonthdays4(year, month)
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.
monthdatescalendar(year, month)
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven datetime.date objects.
monthdays2calendar(year, month)
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.
monthdayscalendar(year, month)
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven day numbers.
yeardatescalendar(year, width=3)
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.
yeardays2calendar(year, width=3)
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.
yeardayscalendar(year, width=3)
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. | python.library.calendar#calendar.Calendar |
calendar.calendar(year, w=2, l=1, c=6, m=3)
Returns a 3-column calendar for an entire year as a multi-line string using the formatyear() of the TextCalendar class. | python.library.calendar#calendar.calendar |
itermonthdates(year, month)
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. | python.library.calendar#calendar.Calendar.itermonthdates |
itermonthdays(year, month)
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. | python.library.calendar#calendar.Calendar.itermonthdays |
itermonthdays2(year, month)
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. | python.library.calendar#calendar.Calendar.itermonthdays2 |
itermonthdays3(year, month)
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. | python.library.calendar#calendar.Calendar.itermonthdays3 |
itermonthdays4(year, month)
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. | python.library.calendar#calendar.Calendar.itermonthdays4 |
iterweekdays()
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. | python.library.calendar#calendar.Calendar.iterweekdays |
monthdatescalendar(year, month)
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven datetime.date objects. | python.library.calendar#calendar.Calendar.monthdatescalendar |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.