Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (11.4k points)

There appear to be two different ways to convert a string to bytes, as seen in the answers to TypeError: 'str' does not support the buffer interface

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')

1 Answer

0 votes
by (106k points)
  • You can do the conversion by performing following code:-

my_str = "hello world" 

my_str_as_bytes = str.encode(my_str) 


my_decoded_str = my_str_as_bytes.decode() type(my_decoded_str)




Related questions

0 votes
1 answer
asked Oct 11, 2019 in Python by Sammy (47.6k points)
+3 votes
2 answers
asked May 24, 2019 in Python by Krishna (2.6k points)
0 votes
1 answer
0 votes
1 answer
asked Sep 10, 2019 in Python by Sammy (47.6k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers


94k users

Browse Categories