目标:
(在Python 3.6中(
确定传递给函数的字符串是否应解释为Int、Float或string。希望(使用内置的Python函数(不需要编写自己的函数,该函数在Python中遍历字符。
基本上,就像atoi()
和atoll()
函数一样,如果整个缓冲区被成功读取。
应标记为Int:
- "-1234">
- "1234">
- "1234">
应标记为Float:
- "-1.234〃
- "1.234〃
- "1.234〃
应标记为字符串:
- "972-727-9857">
- "1_2 345〃
- "asdf">
已尝试:
使用强制转换:
def find_type(s):
try:
int(s)
return int
except ValueError:
pass
try:
float(s)
return float
except ValueError:
pass
return str
^上面的缺点是:
- "1_2 34〃->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…写这篇文章
如何将字符串解析为float或int?
^我找到了上面的,但它并不能完全解决我的问题。
只需检查下划线:
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'>
Hrmm。。。在发布这个问题后,我想到了这个:
使用Regex:
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
我想这可能是唯一/最好的方法。