Lakshin Karunaratne
Lakshin Karunaratne

Reputation: 455

How to convert byte string to bytes in Python?

I'm a total beginner in python and i have a set of byte values in a CSV file which i want to process. Sample values are mentioned below

"b'\xaa'"
"b'\x04'"
    data1 = pd.read_csv("test.csv", usecols=[1])
    for value in data1.values.flatten():
       print(int.from_bytes(value, byteorder='big'))

When running the above code i get the error saying

TypeError: cannot convert 'str' object to bytes

because it is read as a string. How could I pass this string as bytes and use it in the above code?

I'm using Python 3.7.

Upvotes: 1

Views: 610

Answers (1)

abhilb
abhilb

Reputation: 5757

You can try

>>> x = "b'\xaa'"
>>> int.from_bytes(x.encode('utf-8'), byteorder="big")
421573863975
>>> x = "b'\x04'"
>>> int.from_bytes(x.encode('utf-8'), byteorder="big")
1646724135

Upvotes: 1

Related Questions