In this tutorial, we will learn about the Python bytes() method with the help of examples. Nội dung chính - bytes() Syntax
- bytes() Parameters
- bytes() Return Value
- Example 1: Convert string to bytes
- Example 2: Create a byte of given integer size
- Example 3: Convert iterable list to bytes
- Python bytes() example
- Example 1: Convert string to bytes
- Example 2: Array of bytes from an integer
- Example 3: Null parameters with bytes()
- Example 4: Demonstrating
byte() on integers, none and iterables
- Behavior of Bytes with Strings
- Example: Demonstration of bytes() using string
- How do you calculate bytes in Python?
- What is the bytes type in Python?
The bytes() method returns an immutable bytes object initialized with the given size and data. Examplemessage = 'Python is fun'
# convert string to bytes
byte_message = bytes(message, 'utf-8')
print(byte_message)
# Output: b'Python is fun'
bytes() SyntaxThe
syntax of bytes() method is: bytes([source[, encoding[, errors]]]) bytes() method returns a bytes object which is an immutable (cannot be modified) sequence of integers in the range 0 <=x < 256 .
If you want to use the mutable version, use the bytearray() method.
bytes() Parametersbytes() takes three optional parameters:
- source (Optional) - source to initialize the array of bytes.
- encoding (Optional) - if the source is a
string, the encoding of the string.
- errors (Optional) - if the source is a string, the action to take when the encoding conversion fails (Read more: String encoding)
The source parameter can be used to initialize the byte array in the following ways:
Type | Description |
---|
String
| Converts the string to bytes using str.encode() Must also provide encoding and optionally errors
| Integer
| Creates an array of provided size, all initialized to null
| Object
| A read-only buffer of the object will be used to initialize the byte array
| Iterable
| Creates an array of size equal to the iterable count and initialized to the iterable elements Must be iterable of integers between 0 <= x < 256
| No source (arguments)
| Creates an array of size 0
|
bytes() Return ValueThe bytes() method returns a bytes object of the given size and initialization values.
Example 1: Convert string to bytesstring = "Python is interesting."
# string with encoding 'utf-8'
arr = bytes(string, 'utf-8')
print(arr)
Output b'Python is interesting.'
Example 2: Create a byte of given integer sizesize = 5
arr = bytes(size)
print(arr)
Output b'\x00\x00\x00\x00\x00'
Example 3: Convert iterable list to bytesrList = [1, 2, 3, 4, 5]
arr = bytes(rList)
print(arr)
Output b'\x01\x02\x03\x04\x05' Python byte() function converts an object to an immutable byte-represented object of given size and data. Syntax : bytes(src, enc, err) Parameters : - src : The source object which has to be converted
- enc : The encoding required
in case object is a string
- err : Way to handle error in case the string conversion fails.
Returns : Byte immutable object consisting of unicode 0-256 characters according to src type. - integer : Returns array of size initialized to null
- iterable : Returns array of iterable size with elements equal to iterable elements( 0-256 )
- string : Returns the encoded
string acc. to enc and if encoding fails, performs action according to err specified.
- no arguments : Returns array of size 0.
Python bytes() exampleExample 1: Convert string to bytes In this example, we are going to convert string to bytes using the Python bytes() function, for this we take a variable with string and pass it into the bytes()
function with UTF-8 parameters. UTF-8 is capable of encoding all 1,112,064 valid character code points in Unicode using one to four one-byte code units Python3str = "Welcome to Geeksforgeeks"
arr = bytes( str , 'utf-8' )
print (arr)
Output: b'Welcome to Geeksforgeeks' Example 2: Array of bytes from an integerIn this example, we are going to see how to get an array of bytes from
an integer using the Python bytes() function, for this we will pass the integer into the bytes() function. Python3number = 12
result = bytes(number)
print (result)
Output: b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' Example 3: Null parameters with bytes()When we pass nothing in bytes() function then it creates an array of size 0. Python3Output: b'' Example 4: Demonstrating byte() on integers, none and iterablesPython3a = 4
lis1 = [ 1 , 2 , 3 , 4 , 5 ]
print ( "Byte conversion with no arguments : " + str (bytes()))
print ( "The integer conversion results in : " + str (bytes(a)))
print ( "The iterable conversion results in : " + str (bytes(lis1)))
Output:
Byte conversion with no arguments : b''
The integer conversion results in : b'\x00\x00\x00\x00'
The iterable conversion results in : b'\x01\x02\x03\x04\x05' Behavior of Bytes with Strings Bytes accept a string as an argument and require an encoding scheme with it to perform it. The most important aspect of this is handling errors in case of encoding failure, some of the error handling schemes defined are : String Error Handlers : - strict : Raises the default UnicodeDecodeError in case of encode failure.
- ignore : Ignores the unencodable character and encodes the remaining string.
- replace : Replaces the unencodable character with a ‘?’.
Example: Demonstration of bytes() using stringPython3str1 = 'GeeksfÖrGeeks'
print ( "Byte conversion with ignore error : " +
str (bytes(str1, 'ascii' , errors = 'ignore' )))
print ( "Byte conversion with replace error : "
+
str (bytes(str1, 'ascii' , errors = 'replace' )))
print ( "Byte conversion with strict error : " +
str (bytes(str1, 'ascii' , errors = 'strict' )))
Output: Byte conversion with ignore error : b'GeeksfrGeeks'
Byte conversion with replace error : b'Geeksf?rGeeks' Exception : UnicodeEncodeError: ‘ascii’ codec can’t encode character ‘\xd6’ in position 6: ordinal not in range(128)
How do you calculate bytes in
Python?Use the len() function to get the length of a bytes object, e.g. len(my_bytes) . The len() function returns the length (the number of items) of an object and can be passed a sequence (a bytes, string, list, tuple or range) or a collection (a dictionary, set, or frozen set). What is the bytes type in Python?In short, the bytes type is a sequence of bytes that have been encoded and are ready to be stored in
memory/disk. There are many types of encodings (utf-8, utf-16, windows-1255), which all handle the bytes differently. The bytes object can be decoded into a str type. The str type is a sequence of unicode characters.
|