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.
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)
The output of the above program is as follows -
b'TutorialsPoint'
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)
The following is the output of the above program -
b'Welcome'
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)
The output of the above program is as follows -
b'Vanakam'
