首页 > 解决方案 > 检查数字是否有小数的最快方法

问题描述

我正在输入检查数字是正数、负数以及是否有小数的代码。有没有更快的方法来检查小数?

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()

标签: python

解决方案


跟进评论(1 , 2):OP问题中提出的代码很好。

但是,如果我们想避免将字符串转换为数字类型和使用异常的成本,也可以依赖正则表达式来直接断言符号和所提供文字的类型。

例如,通过编写如下内容:

#!/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: ")))

推荐阅读