在Python中将字符串解释为其他数据类型 [英] Interpreting Strings as Other Data Types in Python

查看:108
本文介绍了在Python中将字符串解释为其他数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将文件读入python 2.4,其结构如下:

I'm reading a file into python 2.4 that's structured like this:

field1: 7
field2: "Hello, world!"
field3: 6.2

这个想法是将其解析为一个字典,该字典以fieldfoo作为键,并将冒号后面的值作为值.

The idea is to parse it into a dictionary that takes fieldfoo as the key and whatever comes after the colon as the value.

我想将冒号后面的内容转换为它的实际"数据类型,即'7'应该转换为int"Hello, world!"转换为字符串,等等.唯一需要的数据类型要解析的是整数,浮点数和字符串. python标准库中是否有一个函数可以使您轻松进行此转换?

I want to convert whatever is after the colon to it's "actual" data type, that is, '7' should be converted to an int, "Hello, world!" to a string, etc. The only data types that need to be parsed are ints, floats and strings. Is there a function in the python standard library that would allow one to make this conversion easily?

我应该写的唯一的东西是我写的,因此(至少在这种情况下)安全性不是问题.

The only things this should be used to parse were written by me, so (at least in this case) safety is not an issue.

推荐答案

对于较旧的python版本,例如所要求的版本,可以使用eval函数,但为了减少邪恶, dict作为全局名称空间应用作第二个参数,以避免函数调用.

For older python versions, like the one being asked, the eval function can be used but, to reduce evilness, a dict to be the global namespace should be used as second argument to avoid function calls.

>>> [eval(i, {"__builtins__":None}) for i in ['6.2', '"Hello, world!"', '7']]
[6.2, 'Hello, world!', 7]

这篇关于在Python中将字符串解释为其他数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆