python-3.x - Python3:字符串中的字符应该被视为 Int、Float 还是 String?
问题描述
目标:
(在 Python 3.6 中)
确定传递给函数的字符串是否应解释为 Int、Float 或 String。希望(使用内置的 Python 函数)不需要编写我自己的在 Python 中遍历字符的函数。
基本上,就像 Catoi()
和atoll()
函数一样,如果成功读取了整个缓冲区。
应标记为 Int:
- “-1234”
- “1234”
- “+1234”
应标记为浮动:
- “-1.234”
- “1.234”
- “+1.234”
应标记为字符串:
- “972-727-9857”
- “1_2345”
- “自卫队”
试过:
使用演员表:
def find_type(s):
try:
int(s)
return int
except ValueError:
pass
try:
float(s)
return float
except ValueError:
pass
return str
^以上有缺点:
- “1_234”-> 整数(1234)
使用 AST
import ast
def find_type(s):
obj_type = ast.literal_eval(s)
if isinstance(obj_type, float):
return float
if isinstance(obj_type, int):
return int
return str
^ 这也有以下问题:
- “123_123”-> 整数(123123)
- “123-123-123”-> 整数(-123)
问题
我是否注定要编写自己的行走字符的函数?...我打算用 C 来写这个...
^ 我找到了上述内容,但它并不能完全解决我的问题。
解决方案
只需检查下划线:
def find_type(s):
if '_' in s:
return str
for typ in (int,float):
try:
typ(s)
return typ
except ValueError:
pass
return str
trials = '-1234','1234','+1234','-1.234','1.234','+1.234','972-727-9857','1_2345','asdf'
for trial in trials:
print(trial,find_type(trial))
输出:
-1234 <class 'int'>
1234 <class 'int'>
+1234 <class 'int'>
-1.234 <class 'float'>
1.234 <class 'float'>
+1.234 <class 'float'>
972-727-9857 <class 'str'>
1_2345 <class 'str'>
asdf <class 'str'>
推荐阅读
- android - 旧布局显示新活动
- python-3.x - dicscord.py 重写不让我发送图像
- amazon-web-services - 将 AWS RDS 从标准版“降级”到 Web 版
- groovy - Groovy 复制文件,修改值并保存
- java - TWA 应用程序错误:java.lang.NoClassDefFoundError
- ios - 从 UITableViewCell 中删除单个分隔线
- wso2 - WSO2IS 5.10.0 - deployment.toml 中缺少用户存储属性
- python-3.x - 将输入字符串覆盖为整数
- junit - 由于 Bcrypt 加密,在单元测试期间更新 CRUD 出现问题
- java - 无法在显示图标之间延迟