python - 检查数字是否有小数的最快方法
问题描述
我正在输入检查数字是正数、负数以及是否有小数的代码。有没有更快的方法来检查小数?
n = input("Type a number: ")
try:
n = int(n)
if n > 0:
print("n is positive")
elif n < 0:
print("n is negative")
else:
print("n is zero")
except ValueError:
n = float(n)
if n > 0:
print("n is positive and decimal")
elif n < 0:
print("n is negative and decimal")
else:
print("n is zero")
print(n)
input()
解决方案
但是,如果我们想避免将字符串转换为数字类型和使用异常的成本,也可以依赖正则表达式来直接断言符号和所提供文字的类型。
例如,通过编写如下内容:
#!/usr/bin/env python3
import re
def process(txt):
pat = re.compile(r'^(-)?[0-9]+(\.[0-9]+)?$')
grep = pat.match(txt)
print(txt, 'is:')
if grep is None:
print('not a numeric string')
else:
if grep.group(1) is None:
print('some ', end='')
else:
print('some negative ', end='')
if grep.group(2) is None:
print('integer')
else:
print('decimal')
process('-12')
process('-12.5')
process('12')
process('12.5')
process('foo')
process(500*'9')
process(str(input("Type a number: ")))
推荐阅读
- python - 获取数组或字符串的大小
- cytoscape - Cytoscape 已安装在我的 Mac 上,但无法打开
- node.js - Node.js Express 回调执行问题
- angular - OidcClient.readSigninResponseState:在存储中找不到匹配的状态 - oidc-client-js (Angular)
- html - css中position属性的absolute元素的主要用途和实际用途是什么?它如何在现代网站中使用?
- pyqt5 - 根据单独单元格中的值为 QTableView 单元格着色
- ruby-on-rails - 将静态元数据存储在 ruby 文件中的最佳方法
- iphone - iPhone / iPad 不会在 AWL ELB 后面加载网站或子域托管
- html - 尝试在样式中插入打字稿元素时出现术语预期错误
- spring-boot - 如何在 PCF 管理的 RabbitMQ 上使用 x-delay 消息头(标准计划)