Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

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'
Updated on: 2025-04-21T15:59:38+05:30

259 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements