python - Whether eval() better than self-analysis? -
here situation, have string follows
'a':1 'b':2 'c':3
i want turn dict, have 2 options:
split string
' '
,':'
put pairsdict
.replace
' '
','
, append'{'
, ,'}'
string , useeval()
dict
.
so question 1 faster?
i this:
import ast result = ast.literal_eval(''.join(["{", s.replace(" ", ", "), "}"]))
you can (although difference may negligible):
import ast result = ast.literal_eval("{" + s.replace(" ", ", ") + "}")
it's better use ast.literal_eval
it's safer purpose using eval()
.
Comments
Post a Comment