Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
How would you convert string to bytes in Python 3?
In Python, strings and bytes are two different types of data, where the strings are the sequences of unicode characters used for text representation, while bytes are sequences of bytes used for binary data.
Converting strings to bytes is used when we want to work with the raw binary data or perform low-level operations. This can be done by using the built-in encode() method or the bytes() constructor.
Using Python encode() Method
The Python encode() method is used to convert the string into bytes object using the specified encoding format.
Syntax
Following is the syntax for Python encode() method −
string.encode(encoding=encoding, errors=errors)
Example 1
Let's look at the following example, where we are going to convert the string into bytes object using the 'UTF-8' encoding −
demo = "TutorialsPoint"
result = demo.encode('utf-8')
print(result)
print(type(result))
The output of the above program is as follows −
b'TutorialsPoint' <class 'bytes'>
Using Python bytes() Constructor
The bytes() constructor is another method to convert strings to bytes by passing the string and specifying the encoding type.
Example 2
Consider the following example, where we are going to use the bytes() constructor by passing the string and specifying the encoding type −
str1 = "Welcome" result = bytes(str1, encoding='utf-8') print(result) print(type(result))
The output of the above program is as follows −
b'Welcome' <class 'bytes'>
Example 3
In the following example, we are going to perform the conversion using the ASCII encoding −
str1 = "Vanakam"
result = str1.encode('ascii')
print(result)
print("Length of original string:", len(str1))
print("Length of bytes object:", len(result))
The output of the above program is as follows −
b'Vanakam' Length of original string: 7 Length of bytes object: 7
Example 4
Here's an example showing different encoding formats and their outputs −
text = "Hello Python"
# UTF-8 encoding
utf8_bytes = text.encode('utf-8')
print("UTF-8:", utf8_bytes)
# ASCII encoding
ascii_bytes = text.encode('ascii')
print("ASCII:", ascii_bytes)
# Latin-1 encoding
latin1_bytes = text.encode('latin-1')
print("Latin-1:", latin1_bytes)
The output of the above program is as follows −
UTF-8: b'Hello Python' ASCII: b'Hello Python' Latin-1: b'Hello Python'
Both the encode() method and bytes() constructor are effective ways to convert strings to bytes in Python 3, with UTF-8 being the most commonly used encoding format.
