Convert bytes to a string
Decode the bytes
object to produce a string:
>>> b"abcde".decode("utf-8")
'abcde'
The above example assumes that the bytes
object is in UTF-8, because it is a common encoding. However, you should use the encoding your data is actually in!
How do I convert a Python 3 byte-string variable into a regular string?
You had it nearly right in the last line. You want
str(bytes_string, 'utf-8')
because the type of bytes_string
is bytes
, the same as the type of b'abc'
.
Converting Byte to String and Back Properly in Python3?
Note: Some codes found on the Internet.
You could try to convert it to hex format. Then it is easy to convert it back to byte format.
Sample code to convert bytes to string:
hex_str = rnd_bytes.hex()
Here is how 'hex_str' looks like:
'771296b8'
And code for converting it back to bytes:
new_rnd_bytes = bytes.fromhex(hex_str)
The result is:
b'w\x12\x96\xb8'
For processing you can use:
readable_str = ''.join(chr(int(hex_str[i:i+2], 16)) for i in range(0, len(hex_str), 2))
But newer try to encode readable string, here is how readable string looks like:
'w\x12\x96¸'
After processing readable string convert it back to hex format before converting it back to bytes string like:
hex_str = ''.join([str(hex(ord(i)))[2:4] for i in readable_str])
convert a byte array to string
You could convert the byte array to a char array, and then construct a string from that
scala> val bytes = Array[Byte]('a','b','c','d')
bytes: Array[Byte] = Array(97, 98, 99, 100)
scala> (bytes.map(_.toChar)).mkString
res10: String = abcd
scala>
How to Convert Byte Array back into string?
If s
is that byte string:
for x in s:
print(f'{x:08b}')
Instead of print
, you can do what you like with the strings of 0's and 1's.
It is unnecessarily inefficient to go through strings of 0 and 1 characters for encoding and decoding. You should instead assemble and disassemble the bytes directly using the bit operators (<<
, >>
, |
, &
).
How to convert bytes to string in Python 3 to concatenate(serialized_data,signature)
Use .digest()
not .hexdigest()
to get a byte string that can be prepended to the serialized data byte string. Open the file for binary read/write:
import pickle
import json
import hashlib
import hmac
class User(object):
def __init__(self, name):
self.name = name
filename = 'user.file'
KEY = b'secret'
user = User('david')
serialized = pickle.dumps(user)
#calculate the signature
signature = hmac.new(KEY, serialized, hashlib.sha256).digest() # not .hexdigest()
with open(filename, 'wb') as file_object: # binary write
file_object.write(signature + serialized)
with open(filename, 'rb') as file_object: # binary read
raw_data = file_object.read()
if len(raw_data) >= len(signature): # need >= here
read_signature = raw_data[:len(signature)]
read_data = raw_data[len(signature):]
computed_signature = hmac.new(KEY, read_data, hashlib.sha256).digest() # not .hexdigest()
if hmac.compare_digest(computed_signature, read_signature):
userDeserialized = pickle.loads(read_data)
print (userDeserialized.name)
Output:
david
Bytes not the same when converting from bytes to string to bytes
data_str.encode()
expects data_str
to be the result of data.decode()
.
str(data)
doesn't return a decoded byte string, it returns the printed representation of the byte string, what you would type as a literal in a program. If you want to convert that back to a byte string, use ast.literal_eval()
.
import ast
with open(r'file-path', 'rb') as file:
data = file.read()
str_data = str(data)
new_data = ast.literal_eval(str_data)
print(new_data == data)
Related Topics
How Does Python'S Super() Work With Multiple Inheritance
Why Does "Pip Install" Inside Python Raise a Syntaxerror
How to Make a Python Script Standalone Executable to Run Without Any Dependency
Running Bash Commands in Python
How to Read a Single Character from the User
Adding a Scrollbar to a Group of Widgets in Tkinter
What Does the 'B' Character Do in Front of a String Literal
Pygame Installation Issue in MAC Os
Is It Pythonic to Use List Comprehensions For Just Side Effects
How to Access Object Attribute Given String Corresponding to Name of That Attribute
How to Add Sequential Counter Column on Groups Using Pandas Groupby
Find All Files in a Directory With Extension .Txt in Python
Split a Pandas Column of Lists into Multiple Columns
Difference Between @Staticmethod and @Classmethod