python - 自动将字符串转换为适当的类型
问题描述
我试图找到一个函数让python自动将字符串转换为“最简单”的类型。一些例子:
conversion_function("54") -> returns an int 54
conversion_function("6.34") -> returns a float 6.34
conversion_function("False") -> returns a boolean False
conversion_function("text") -> returns a str "text"
R 有一个名为type.convert的函数来执行此操作。在 python 中执行此操作的方法是什么?是否有现有功能或是否需要创建自定义功能?
解决方案
如果失败,您可以使用ast.literal_eval
, 并回退到不转换(返回原始字符串):
from ast import literal_eval
def simplest_type(s):
try:
return literal_eval(s)
except:
return s
例子:
>>> simplest_type('54')
54
>>> simplest_type('6.34')
6.34
>>> simplest_type('False')
False
>>> simplest_type('text')
'text'
推荐阅读
- c# - 我们可以在项目中创建一个文件夹并由用户而不是 bin 在其中添加图像吗?
- c - 线程 1:signal SIGABRT - Xcode 在执行后崩溃
- php - Composer:非空 PSR-4 前缀必须以命名空间分隔符结尾
- python - 调整梯度提升分类的自定义损失函数
- assembly - commodore 64 smooth scroller on line 1 - is jumping around on the screen if interrupt set on line #0
- java - 带有 Java 的 JSON;将 JSON 对象转换为要通过 Java 套接字发送的 Java 字符串
- jsf - 即使在使用项目阶段和过滤器后,我的 js/css 缓存也无法正常工作,标题日期总是得到更新
- assembly - Round floating-point numbers in NASM
- python - 我在 tkinter 中的按钮不起作用!尝试了一切
- android - 过滤后recyclerview上的searchfilter得到错误的项目选择问题