Skip to content Skip to footer

Pythoneval() 函数!

eval 函数有将字符格式的伪 python 代码转成正常的 python 代码,特别适合于读取 config 文件和获取用户输入格式的转换:

config_args = '[(1,2,3),(4,5,6),(7,8,9)]'

# 如果不用 eval 函数的话,将 str 格式转成 python 字面格式需要如下操作

import re

config_args = re.findall("\d+",config_args)

config_args = list(map(int,img_size))

config_args = [tuple(img_size[i:i+3]) for i in range(0,len(img_size),3)]

print(config_args)

# 而用来 eval 函数仅仅需要一行代码

config_args = eval(config_args)aiF aiF

173***3274@qq.com

4年前 (2022-03-19)