Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert 'binary string' to normal string in Python3?

For example, I have a string like this(return value of subprocess.check_output):

>>> b'a string' b'a string' 

Whatever I did to it, it is always printed with the annoying b' before the string:

>>> print(b'a string') b'a string' >>> print(str(b'a string')) b'a string' 

Does anyone have any ideas about how to use it as a normal string or convert it into a normal string?

like image 737
Hanfei Sun Avatar asked Jul 12 '13 12:07

Hanfei Sun


People also ask

How do you convert a binary to a string in Python?

The binary data is divided into sets of 7 bits because this set of binary as input, returns the corresponding decimal value which is ASCII code of the character of a string. This ASCII code is then converted to string using chr() function.

How do you split a string in binary in Python?

Python split() method is used to split the string into chunks, and it accepts one argument called separator. A separator can be any character or a symbol. If no separators are defined, then it will split the given string and whitespace will be used by default.


2 Answers

Decode it.

>>> b'a string'.decode('ascii') 'a string' 

To get bytes from string, encode it.

>>> 'a string'.encode('ascii') b'a string' 
like image 168
falsetru Avatar answered Oct 15 '22 21:10

falsetru


If the answer from falsetru didn't work you could also try:

>>> b'a string'.decode('utf-8') 'a string' 
like image 32
kame Avatar answered Oct 15 '22 20:10

kame