码迷,mamicode.com
首页 > 其他好文 > 详细

判断一个字符串是否为数字、字母

时间:2020-07-10 14:51:03      阅读:57      评论:0      收藏:0      [点我收藏+]

标签:asc   其他   get   参数   输入参数   targe   number   oar   ons   

fastnumbers参考文档: https://fastnumbers.readthedocs.io,

除了提供fast_float,fast_real等函数来加速builtins API外,此包还提供了isreal, isfloat, isint, isintlike等API,方便调用判断输入是否为float或者int。 比调用float函数或者int函数,然后异常报错后得到判断结果(如代码一)更为优雅;

需要注意的是 num_only,str_only并不是指明输入参数 必须数字[0-9]串或者必须是字符串,而是数据类型是数字或者字符串。

 

代码一:

def isfloat(abc):
    try:
        float(abc)
        return True
    except:
        return False
print(isfloat("abc"))
print(isfloat("-7\n"))

 

 

fastnumbers有一例外是会将非ascii码的纯数字也做判断并返回True,所以需要进行过滤;
isfloat, isint, isreal等函数返回True;  叠加判断是否为ascii吗,防止中文、其他语言的中的数字被判断为float类型; isascii代码如代码段二:
   
if isfloat(segs[0]) and isascii(segs[0]):

 

代码二:
def is_ascii(str_):
    try:
        if str_.encode("ascii"):
            return True
    except:
        return False

 

 

 
 

判断一个字符串是否为数字、字母

标签:asc   其他   get   参数   输入参数   targe   number   oar   ons   

原文地址:https://www.cnblogs.com/operaculus/p/13266556.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!