【发布时间】: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