检查字符串是否为整数或浮点数

23

所以我正在创建一个程序来展示数字系统,然而我在第一关遇到了问题。程序将会从用户那里得到一个数字,之后将使用该数字贯穿整个程序以解释一些计算机科学概念。

在讲解第一个部分——数字系统时,程序将会告诉用户它是什么类型的数字。我通过将字符串转换为浮点数来实现这一点。如果浮点数只有'.0',则将其转换为整数。

目前,我正在使用以下代码:

while CorrectNumber == False:
try:
    Number = float(NumberString) - 0
    print (Number)
except:
    print ("Error! Not a number!")

这很有用,因为它可以显示用户是否输入了一个数字。然而,我不确定如何检查小数点后面的值,以决定是否应该将其转换为整数。有什么建议吗?


解决方案:https://stackoverflow.com/a/64132078/8321339 - Vishal Gupta
11个回答

-1

我将本·穆罕默德的回答改写如下(数字也可能为负数):

from numpy import nan, isnan

def is_valid_number(s):
    if (s.find('-') <= 0) and s.replace('-', '', 1).isdigit():
        if (s.count('-') == 0):
            s_type = 'Positive Integer'
        else:
            s_type = 'Negative Integer'
    elif (s.find('-') <= 0) and (s.count('.') < 2) and \
         (s.replace('-', '', 1).replace('.', '', 1).isdigit()):
        if (s.count('-') == 0):
            s_type = 'Positive Float'
        else:
            s_type = 'Negative Float'
    else:
        s_type = "Not alphanumeric!"
    return('{}\t is {}'.format(s, s_type))

例子:

nums = ['12', '-34', '12.3', '-12.0', '123.0-02', '12!','5-6', '3.45.67']
for num in nums:
    print(is_valid_number(num))

结果:

12   is Positive Integer
-34  is Negative Integer
12.3     is Positive Float
-12.0    is Negative Float
123.0-02     is Not alphanumeric!
12!  is Not alphanumeric!
5-6  is Not alphanumeric!
3.45.67  is Not alphanumeric!

最小代码:

from numpy import nan, isnan

def str2num(s):
    if (s.find('-') <= 0) and s.replace('-', '', 1).isdigit():
        return(int(s))
    elif (s.find('-') <= 0) and (s.count('.') < 2) and \
         (s.replace('-', '', 1).replace('.', '', 1).isdigit()):
        return(float(s))
    else:
        return(nan)

例子:

nums = ['12', '-34', '12.3', '-12.0', '123.0-02', '12!','5-6', '3.45.67']
for num in nums:
    x = str2num(num)
    if not isnan(x):
        print('x =', x) # .... or do something else

结果:
x = 12
x = -34
x = 12.3
x = -12.0

这并没有回答问题。一旦您拥有足够的声望,您将能够评论任何帖子;相反,提供不需要询问者澄清的答案。- 来自审核 - aaossa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接