Home » Python

Best way to convert string to bytes in Python3

Python | Converting string to bytes: Here, we are going to learn about the best way to convert string to bytes in Python3.
Submitted by Sapna Deraje Radhakrishna, on January 19, 2020

To convert a string to bytes, there are more than one way,

Approach 1: use encode() method

test_str = "include_help"

test_bytes = test_str.encode()



<class 'str'>
<class 'bytes'>

In python3, the first parameter to encode() defaults to 'utf-8'. This approach is also supposedly faster because the default argument results in NULL in the C code.

Approach 2: use bytes() constructor

test_str = "include_help"

test_bytes_v2 = bytes(test_str, 'utf-8')



<class 'bytes'>

Using the bytes constructor gives more options than just encoding the string. However, for encoding a string the approach1, is more pythonic than using a constructor, because it is more readable.

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.