(在Python 3.6中)
确定传递给函数的字符串应解释为Int,Float还是String。希望(具有内置的Python函数)无需编写自己的函数即可在Python中遍历字符。
基本上,像Catoi()
和atoll()
函数一样,如果成功读取了整个缓冲区。
def find_type(s):
try:
int(s)
return int
except ValueError:
pass
try:
float(s)
return float
except ValueError:
pass
return str
^上面有缺点:
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语言编写...
^我发现了上面的内容,但是并不能完全解决我的问题。
嗯...发布此问题后,我想到了这一点:
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
我想这可能是唯一/最好的方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句