ast.literal_eval
eval函數在python中做數據類型的轉換還是很有用的。它的作用就是把數據還原成它本身或者是能夠轉化成的數據類型。
那么eval和ast.literal_val()的區別是什么呢?
eval在做計算前并不知道需要轉化的內容是不是合法的(安全的)python數據類型。只是在調用函數的時候去計算。如果被計算的內容不是合法的python類型就會拋出異常。
ast.literal則會判斷需要計算的內容計算后是不是合法的python類型,如果是則進行運算,否則就不進行運算。
------------------------------引用自stackoverflow--------------------------------
datamap = eval(raw_input('Provide some data here: ')?means that you actually evaluate the code?before?you deem it to be unsafe or not. It evaluates the code as soon as the function is called. See also?the dangers of?eval.
ast.literal_eval?raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.
Use?ast.literal_eval?whenever you need?eval. If you have Python expressions as an input that you want to evaluate, you shouldn't (have them).
---------------------?
作者:zhiqiang21?
來源:CSDN?
原文:https://blog.csdn.net/yisuowushinian/article/details/45644299?
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!
總結
以上是生活随笔為你收集整理的ast.literal_eval的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python陷阱:为什么不能用可变对象作
- 下一篇: 双下划线开头的变量实现了类私有变量功能