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

简介: 实现Python代码,输入数字,然后输出这个数字的三倍。 >>> n = input("Enter a number: ") Enter a number: 6 >>> print(f"{n} * 3 = {n*3}") 6 * 3 = 666 input函数总是返回字符串。

实现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
相关文章
|
12天前
|
程序员 开发者 Python
Python网络编程基础(Socket编程) 错误处理和异常处理的最佳实践
【4月更文挑战第11天】在网络编程中,错误处理和异常管理不仅是为了程序的健壮性,也是为了提供清晰的用户反馈以及优雅的故障恢复。在前面的章节中,我们讨论了如何使用`try-except`语句来处理网络错误。现在,我们将深入探讨错误处理和异常处理的最佳实践。
|
30天前
|
程序员 开发者 Python
Python错误与异常处理详解
Python提供强大的错误和异常处理机制,包括语法错误(编译时)和运行时错误。异常处理通过try-except语句实现,优雅地处理运行时错误。例如,尝试除以零会引发`ZeroDivisionError`,可通过except捕获并处理。可以使用多个except处理不同类型的异常,或者用`Exception`捕获所有异常。此外,用raise语句可手动抛出异常,增强代码健壮性。理解并运用这些机制能提升Python编程水平。
|
2月前
|
Rust Java 测试技术
Python 数值中的下划线是怎么回事?
Python 数值中的下划线是怎么回事?
28 1
|
1月前
|
Python
解释 Python 中的异常处理机制。
解释 Python 中的异常处理机制。
21 0
|
2月前
|
开发者 Python
Python中的异常处理:原理与实践
Python中的异常处理:原理与实践
|
1月前
|
Python
python中文件和异常处理方法(二)
python中文件和异常处理方法(二)
13 0
|
1月前
|
Python
python中文件和异常处理方法(一)
python中文件和异常处理方法(一)
29 0
|
1月前
|
Python
python中文件和异常处理方法(三)
python中文件和异常处理方法(三)
20 0
|
1月前
|
Python
Python异常处理
Python异常处理
12 0
|
5天前
|
程序员 数据库连接 索引
《Python 简易速速上手小册》第5章:Python 常见错误和异常处理(2024 最新版)
《Python 简易速速上手小册》第5章:Python 常见错误和异常处理(2024 最新版)
22 1