Python技巧: 用isnumeric等代替数值异常处理

实现Python代码,输入数字,然后输出这个数字的三倍。

>>> n = input("Enter a number: ")
Enter a number: 6
>>> print(f"{n} * 3 = {n*3}")
6 * 3 = 666

input函数总是返回字符串。可以通过int转换字符串为整数:

>>> n = int(n)
>>> print(f"{n} * 3 = {n*3}")
6 * 3 = 18

但是,如果输入不是数值,则会报错:

Enter a number: abcd
ValueError: invalid literal for int() with base 10: 'abcd'

比较常用的方法是在“try”块中运行转换,并捕获我们可能获得的任何异常。但字符串的isdigit方法可以更优雅地解决这个问题。

>>> '1234'.isdigit()
True
>>> '1234 '.isdigit()  # space at the end
False
>>> '1234a'.isdigit()  # letter at the end
False
>>> 'a1234'.isdigit()  # letter at the start
False
>>> '12.34'.isdigit()  # decimal point
False
>>> ''.isdigit()   # empty string
False

str.isdigit对正则表达式'^ d + $'返回True。

>>> n = input("Enter a number: ")
>>> if n.isdigit():
        n = int(n)
        print(f"{n} * 3 = {n*3}")

Python还包括另一方法str.isnumeric,他们有什么区别?

>>> n = input("Enter a number: ")
>>> if n.numeric():
        n = int(n)
        print(f"{n} * 3 = {n*3}")

字符串只包含数字0-9时str.isdigit返回True。str.isnumeric则还能识别英语意外语言的数值。

>>> '一二三四五'.isdigit()
False
>>> '一二三四五'.isnumeric()
True
>>> int('二')
ValueError: invalid literal for int() with base 10: '二'

str.isdecimal

>>> s = '2²'    # or if you prefer, s = '2' + '\u00B2'
>>> s.isdigit()
True
>>> s.isnumeric()
True
>>> s.isdecimal()
False
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章