简体   繁体   中英

convert string to bytes in python

I have column in a csv that has this value as string:

b'\x00\x00\x00\xc0\x99MC@\x00\x00\x00\xc0\x99MC@\x00\x00\x00\xc0\x99MC@\x00\x00\x00\xc0\x99MC@\x00\x00\x00\xc0\x99MC@\x00\x00\x00\xc0\x99MC@'

How can I convert this string in a bytes object in python?

I tried bytes(string_var, 'utf-8') but I got:

b"b'\\x00\\x00\\x00\\xc0\\x99MC@\\x00\\x00\\x00\\xc0\\x99MC@\\x00\\x00\\x00\\xc0\\x99MC@\\x00\\x00\\x00\\xc0\\x99MC@\\x00\\x00\\x00\\xc0\\x99MC@\\x00\\x00\\x00\\xc0\\x99MC@'"

I am reading the csv file with pandas

thanks in advance

[edit]

answers to comments:

1- my expected result is: b'\x00\x00\x00\xc0\x99MC@\x00\x00\x00\xc0\x99MC@\x00\x00\x00\xc0\x99MC@\x00\x00\x00\xc0\x99MC@\x00\x00\x00\xc0\x99MC@\x00\x00\x00\xc0\x99MC@' (with only one 'b' and object type as bytes and not string)

2-I got this csv from: sql with byte array column => pandas dataframe => csv file

ps: before create csv file from pandas I use this command:

blob['Raw'] = blob['Raw'].apply(lambda x: x.tobytes())

otherwise, the csv file will store '<memory at 0x7f697cdc9d08>' string

I have column in a csv that has this value as string:

b'\x00\x00\x00\xc0\x99MC@\x00\x00\x00\xc0\x99MC@\x00\x00\x00\xc0\x99MC@\x00\x00\x00\xc0\x99MC@\x00\x00\x00\xc0\x99MC@\x00\x00\x00\xc0\x99MC@'

How can I convert this string in a bytes object in python?

I tried bytes(string_var, 'utf-8') but I got:

b"b'\\x00\\x00\\x00\\xc0\\x99MC@\\x00\\x00\\x00\\xc0\\x99MC@\\x00\\x00\\x00\\xc0\\x99MC@\\x00\\x00\\x00\\xc0\\x99MC@\\x00\\x00\\x00\\xc0\\x99MC@\\x00\\x00\\x00\\xc0\\x99MC@'"

I am reading the csv file with pandas

thanks in advance

[edit]

answers to comments:

1- my expected result is: b'\x00\x00\x00\xc0\x99MC@\x00\x00\x00\xc0\x99MC@\x00\x00\x00\xc0\x99MC@\x00\x00\x00\xc0\x99MC@\x00\x00\x00\xc0\x99MC@\x00\x00\x00\xc0\x99MC@' (with only one 'b' and object type as bytes and not string)

2-I got this csv from: sql with byte array column => pandas dataframe => csv file

ps: before create csv file from pandas I use this command:

blob['Raw'] = blob['Raw'].apply(lambda x: x.tobytes())

otherwise, the csv file will store '<memory at 0x7f697cdc9d08>' string

@Barmar is lifesaver

I usedast.literal_eval and worked:

from ast import literal_eval

blob_csv['Raw'] = blob_csv['Raw'].apply(lambda x: literal_eval(str(x)))

Thanks to Barmar and How to use ast.literal_eval in a pandas dataframe and handle exceptions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM