Best way to convert string to bytes in Python

0 votes

There appear to be two different ways to convert a string to bytes, 

Which of these methods would be better or more Pythonic? Or is it just a matter of personal preference?

b = bytes(mystring, 'utf-8')

b = mystring.encode('utf-8')
Dec 28, 2020 in Python by Roshni
• 10,480 points
30,849 views

3 answers to this question.

0 votes

So bytes can do much more than just encode a string. It's Pythonic that it would allow you to call the constructor with any type of source parameter that makes sense.

For encoding a string, I think that some_string.encode(encoding) is more Pythonic than using the constructor, because it is the most self documenting -- "take this string and encode it with this encoding" is clearer than bytes(some_string, encoding) -- there is no explicit verb when you use the constructor.

answered Dec 28, 2020 by Gitika
• 65,770 points
0 votes

 Using bytes(str, enc)

String can be converted to bytes using the generic bytes function. This function internally points to CPython Library which implicitly calls the encode function for converting the string to specified encoding.

# Python code to demonstrate

# convert string to byte 

# Using bytes(str, enc)

  

# initializing string 

test_string = "EDUREKA is best"

  

# printing original string 

print("The original string : " + str(test_string))

  

# Using bytes(str, enc)

# convert string to byte 

res = bytes(test_string, 'utf-8')

  

# print result

print("The byte converted string is  : " + str(res) + ", type : " + str(type(res)))

Output :

The original string : EDUREKA is best
The byte converted string is  : b' EDUREKA is best', type : <class 'bytes'>
answered Dec 28, 2020 by Nikita
0 votes

We can use the built-in Bytes class in Python to convert a string to bytes: simply pass the string as the first input of the constructor of the Bytes class and then pass the encoding as the second argument.

Printing the object shows a user-friendly textual representation, but the data contained in it is​ in bytes.

string = "Hello World"


# string with encoding 'utf-8'

arr = bytes(string, 'utf-8')

arr2 = bytes(string, 'ascii')


print(arr,'\n')


# actual bytes in the the string

for byte in arr:

    print(byte, end=' ')

print("\n")

for byte in arr2:

    print(byte, end=' ')
answered Dec 28, 2020 by David Samon

Related Questions In Python

0 votes
1 answer

What is the best way to remove accents in a Python unicode string?

Hello @kartik, Some languages have combining diacritics as ...READ MORE

answered May 11, 2020 in Python by Niroj
• 82,840 points
7,310 views
0 votes
1 answer

How to convert date string to date object in python?

Use this :-  >>> datetime.datetime.strptime('24052010', "%d%m%Y").date() datetime.date(2010, 5, 24) Hope ...READ MORE

answered Oct 22, 2018 in Python by Priyaj
• 58,020 points
11,250 views
0 votes
1 answer

Best way to open a socket in Python

Opening sockets in python is pretty simple. ...READ MORE

answered Feb 21, 2019 in Python by SDeb
• 13,300 points
839 views
0 votes
1 answer

Convert string to unicode in Python

Suppose you have a string in ASCII form ...READ MORE

answered Jul 23, 2019 in Python by Gani
12,928 views
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,125 views
0 votes
1 answer

Remove final character from string

Simple: st = "abcdefghij" st = st[:-1] There is ...READ MORE

answered Jan 5, 2021 in Python by Gitika
• 65,770 points
596 views
0 votes
1 answer

Removing surrounding whitespace

Try the strip() function:  s = s.strip() If you ...READ MORE

answered May 4, 2018 in Python by Nietzsche's daemon
• 4,260 points
794 views
0 votes
2 answers

How to convert integer to string in Python?

if You Want to convert int to ...READ MORE

answered Nov 28, 2020 in Python by Rohan
• 200 points
794 views
0 votes
1 answer

How to create a unicode string in python with the string eg: This is a string?

Hey, @Roshni, It is very simple to execute, ...READ MORE

answered Jun 23, 2020 in Python by Gitika
• 65,770 points
834 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP