Convert between str and other buildin data type in Python

Convert a build in data type(int, tuple, list  dict, str) to str is easy. str() can handle this


str(12) => '12'

str([1,2,'One']) => '[1,2,"One"]'

str({1:'One', 2:'Two'}) => "{1:'One', 2:'Two'}"

...

 

 

So how to do the convert from right to left? i.e  '[1,2,"One"]' => [1,2, "One"], "{1:'One', 2:'Two'}" => {1:'One', 2:'Two'}

 

Python's eval() function can do this very gracefully

l = eval('[1,2,"One"]')

d = eval("{1:'One', 2:'Two'}")


will give

l = [1,2,"One"]

and

d={1:'One', 2:'Two'}

posted on 2012-08-13 14:08  bian  阅读(167)  评论(0编辑  收藏  举报

导航