Checking to see if a string is an integer or float

强颜欢笑 提交于 2019-12-01 03:59:43

If the string is convertable to integer, it should be digits only. It should be noted that this approach, as @cwallenpoole said, does NOT work with negative inputs beacuse of the '-' character. You could do:

if NumberString.isdigit():
    Number = int(NumberString)
else:
    Number = float(NumberString)

If you already have Number confirmed as a float, you can always use is_integer (works with negatives):

if Number.is_integer():
    Number = int(Number)

Not sure I follow the question but here is an idea:

test = ['1.1', '2.1', '3.0', '4', '5', '6.12']

for number in test:
    try:
        print(int(number))
    except ValueError:
        print(float(number))

Returns:

1.1
2.1
3.0
4
5
6.12

This checks if the fractional-part has any non-zero digits.

def is_int(n):
    try:
        float_n = float(n)
        int_n = int(float_n)
    except ValueError:
        return False
    else:
        return float_n == int_n

def is_float(n):
    try:
        float_n = float(n)
    except ValueError:
        return False
    else:
        return True

Testing the functions:

nums = ['12', '12.3', '12.0', '123.002']

for num in nums:
    if is_int(num):
        print(num, 'can be safely converted to an integer.')
    elif is_float(num):
        print(num, 'is a float with non-zero digit(s) in the fractional-part.')

It prints:

12 can be safely converted to an integer.
12.3 is a float with non-zero digit(s) in the fractional-part.
12.0 can be safely converted to an integer.
123.002 is a float with non-zero digit(s) in the fractional-part.

Here is the method to check,

a = '10'
if a.isdigit():
   print "Yes it is Integer"
elif a.replace('.','',1).isdigit() and a.count('.') < 2:
   print "Its Float"
else:
   print "Its is Neither Integer Nor Float! Something else"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!