0 votes
1 view
in Python by (11.5k 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 (94.3k points)
  • You can do the conversion by performing following code:-

my_str = "hello world" 

my_str_as_bytes = str.encode(my_str) 

type(my_str_as_bytes) 

my_decoded_str = my_str_as_bytes.decode() type(my_decoded_str)

image

 

 

Related questions

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


Categories

...