【Python】学习笔记:异常处理is_number()

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass
 
    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass
 
    return False
 
# 测试字符串和数字
print(is_number('foo'))   # False
print(is_number('1'))     # True
print(is_number('1.3'))   # True
print(is_number('-1.37')) # True
print(is_number('1e3'))   # True
 
# 测试 Unicode
# 阿拉伯语 5
print(is_number('٥'))  # True
# 泰语 2
print(is_number('๒'))  # True
# 中文数字
print(is_number('四')) # True
# 版权号
print(is_number('©'))  # False

代码来源:菜鸟教程https://www.runoob.com/python3/python3-check-is-number.html

这段  判断字符串是否为数字  的代码真的是让老陌眼前一亮,之前测试is_number()我最多就能想到一些简单的字母,虽然也是利用了unicode的一些规则吧,但是我明显忽略了它包罗万象的库,所以在看到阿拉伯语、泰语的时候真的有种惊喜的感觉!回过头来看函数的定义,真的觉得下面这几行太美妙了! 

import unicodedata
        unicodedata.numeric(s)
        return True

然后再看外面套着的异常处理,第一次看到 try-except 还真是有点不太习惯呢,毕竟在java里面我看到的更多的是try-catch,不过转念一想,通常catch后面跟的都是各种Exception,所以“精简”一下变成try-except也就觉得挺好理解的了~

后来,老陌趁机复习了一下,我发现python有别于之前接触过的一些语言,它在触发/抛出异常时使用的关键字是raise,这个真的是不同于JAVA和PHP的,所以这里老陌觉得需要特别注意一下!(其实后来想想也就是说法不同吧,感觉这就和当初学习“函数”和“方法”是一个意思)。

import java.io.*;
public class className
{
  public void deposit(double amount) throws RemoteException
  {
    // Method implementation
    throw new RemoteException();
  }
  //Remainder of class definition
}
<?php
// 创建一个有异常处理的函数
function checkNum($number)
{
    if($number>1)
    {
        throw new Exception("变量值必须小于等于 1");
    }
        return true;
}
    
// 在 try 块 触发异常
try
{
    checkNum(2);
    // 如果抛出异常,以下文本不会输出
    echo '如果输出该内容,说明 $number 变量';
}
// 捕获异常
catch(Exception $e)
{
    echo 'Message: ' .$e->getMessage();
}
?>
def functionName( level ):
    if level < 1:
        raise Exception("Invalid level!", level)
        # 触发异常后,后面的代码就不会再执行

参考资料:菜鸟教程-Python异常处理https://www.runoob.com/python/python-exceptions.html

菜鸟教程-Java异常处理https://www.runoob.com/java/java-exceptions.html

菜鸟教程-PHP异常处理https://www.runoob.com/php/php-exception.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章