首页 > 解决方案 > Python3:字符串中的字符应该被视为 Int、Float 还是 String?

问题描述

目标:

(在 Python 3.6 中)

确定传递给函数的字符串是否应解释为 Int、Float 或 String。希望(使用内置的 Python 函数)不需要编写我自己的在 Python 中遍历字符的函数。

基本上,就像 Catoi()atoll()函数一样,如果成功读取了整个缓冲区。

应标记为 Int:

应标记为浮动:

应标记为字符串:

试过:

使用演员表:

def find_type(s):
    try:
        int(s)
        return int
    except ValueError:
        pass
    try:
        float(s)
        return float
    except ValueError:
        pass
    return str
 

^以上有缺点:

使用 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

^ 这也有以下问题:


问题

我是否注定要编写自己的行走字符的函数?...我打算用 C 来写这个...

如何将字符串解析为浮点数或整数?

^ 我找到了上述内容,但它并不能完全解决我的问题。

标签: python-3.xtypestype-conversion

解决方案


只需检查下划线:

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'>

推荐阅读