Python--eval()函数

eval()函数将公式字符串转换成公式

a = eval("1+2")
print(a,type(a))  # 3 <class 'int'>

b = eval("True")
print(b,type(b))  # True <class 'bool'>

c = eval("1==2")
print(c,type(c))  # False <class 'bool'>

d = eval("true")
print(d)  # NameError: name 'true' is not defined

eval()函数实现list、dict、tuple与str之间的转化

  • 字符串转换成列表
a = "[1,2,3]"
print(a,type(a))  # [1,2,3] <class 'str'>

b = eval(a)
print(b,type(b))  # [1, 2, 3] <class 'list'>
  • 字符串转换成元组
a = "(1,2,3)"
print(a,type(a))  # (1,2,3) <class 'str'>

b = eval(a)
print(b,type(b))  # (1, 2, 3) <class 'tuple'>
  • 字符串转换成字典
a = "{1:'a',2:2,3:[1,2,3]}"
print(a,type(a))  # {1:'a',2:2,3:[1,2,3]} <class 'str'>

b = eval(a)
print(b,type(b))  # {1: 'a', 2: 2, 3: [1, 2, 3]} <class 'dict'>

 

点赞