[英]How to convert a literal string representation of binary string to a binary string?
我正在嘗試將函數與其他描述字段一起保存到 csv 文件中。 我目前正在使用蒔蘿轉儲保存 function,然后將其轉換為文字字符串並存儲在文件中。 當我加載 csv 文件時,我在將此文字字符串轉換回 function 時遇到問題。 有沒有辦法將二進制字符串的字符串表示形式轉換為二進制字符串? 目前我使用 exec 這樣做,但我認為這不是一個好習慣。
或者還有其他更好的方法可以將 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))
我建議將其保存為十六進制字符串(以下實現假設 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.