简体   繁体   English

如何将二进制字符串的文字字符串表示形式转换为二进制字符串?

[英]How to convert a literal string representation of binary string to a binary string?

I am trying to save functions into a csv file, with other description fields.我正在尝试将函数与其他描述字段一起保存到 csv 文件中。 I am currently saving a function using dill dumps, and then convert it into literal string and store in the file.我目前正在使用莳萝转储保存 function,然后将其转换为文字字符串并存储在文件中。 When I load the csv file, I have a problem in converting this literal string back to the function.当我加载 csv 文件时,我在将此文字字符串转换回 function 时遇到问题。 Is there a way to convert the string representation of binary string into the binary string?有没有办法将二进制字符串的字符串表示形式转换为二进制字符串? Currently I use exec to do so but I suppose it is not a good practice.目前我使用 exec 这样做,但我认为这不是一个好习惯。

Or is there other better way to store a function or binary string into a csv file?或者还有其他更好的方法可以将 function 或二进制字符串存储到 csv 文件中吗?

import dill
def add_one(a):
    return a + 1

output_to_csv_file = str(dill.dumps(add_one)) # output_to_csv_file is the string representation of binary string of add_one
exec("tmp = " + output_to_csv_file) # Now I have tmp storing the binary string
loaded_add_one = dill.loads(tmp)
print(loaded_add_one(2))

I would suggest saving it as a hex string (below implementation assumes python 3.5+)我建议将其保存为十六进制字符串(以下实现假设 python 3.5+)

import dill

tmp = dill.dumps(lambda a: a + 1).hex()
loaded = dill.loads(bytes.fromhex(tmp))
print(loaded(2))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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