【问题标题】:Python3: Should characters in string be treated as Int, Float, or String?Python3:字符串中的字符应该被视为 Int、Float 还是 String?
【发布时间】:2020-10-24 17:58:27
【问题描述】:

目标:

(在 Python 3.6 中)

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

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

应标记为 Int:

  • “-1234”
  • “1234”
  • “+1234”

应标记为浮点数:

  • “-1.234”
  • “1.234”
  • “+1.234”

应标记为字符串:

  • “972-727-9857”
  • “1_2345”
  • “asdf”

试过了:

使用演员表:

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

^以上有缺点:

  • "1_234" -> int(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" -> int(123123)
  • “123-123-123”-> int(-123)

问题

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

How do I parse a string to a float or int?

^我找到了上面的,但它并没有完全解决我的问题。

【问题讨论】:

  • 好吧,您可以在第一种方法中轻松检查 if '_' in s: return str 作为边缘情况
  • “1.23E-1”怎么样,代表0.123?

标签: python-3.x types type-conversion


【解决方案1】:

只需检查下划线:

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

【讨论】:

  • 循环上的漂亮模式只需要一次尝试/除了...
【解决方案2】:

嗯……发完这个问题后,我想到了这个:

使用正则表达式:

import re
int_regex = re.compile(r'^(-|\+)?[0-9]+$')
float_regex = re.compile(r'^(-|\+)?([0-9]+)?\.[0-9]+$')

def find_type(s):
    if re.match(int_regex, s):
        return int
    if re.match(float_regex, s):
        return float
    return str

我想这可能是唯一/最好的方法。

【讨论】:

  • “.1”或“1”怎么样。还是“1e-1”?
  • 关于“.1”和“1”的好点。 ...我认为在我的用例中不支持“1e-1”是可以的...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多