Advertisement

python编写自定义函数is_number用于判断字符是否为数字

阅读量:

主要采用try:except:错误异常处理机制,结合float(s)unicodedata.numeric(s)函数,以实现对相关问题的处理。

复制代码
    def is_number(s):
    try:
        float(s)                    # 如果能转换float,说明是个数字
        return True
    except ValueError:
        pass                        # 占位符
    
    try:
        import unicodedata          # 引入Unicodedata模块
        unicodedata.numeric(s)      # 如果能转成numeric,说明是个数字
        return True
    except (TypeError,ValueError):
        pass
    
    return False
    
    # 阿拉伯语5
    print(is_number('٥'))
    # 中文数字亿
    print(is_number('亿'))
    # 连续数字
    print(is_number('一二三'))
    

全部评论 (0)

还没有任何评论哟~