如何检查字符串输入是否为数字?

183

如何检查用户的字符串输入是否为数字(例如,-101等)?

user_input = input("Enter something:")

if type(user_input) == int:
    print("Is a number")
else:
    print("Not a number")

由于 input 总是返回一个字符串,因此上述方法不起作用。


我不知道在“input always returns strings”中,“returns”是否正确。 - Trufa
看起来你正在使用 Python 3.x,那么是的,input 函数始终返回字符串。请参阅:http://docs.python.org/release/3.1.3/library/functions.html#input - Daniel DiPaolo
@DanielDiPaolo:是的,我知道这一点,所以才会问,只是不确定return这个词是否正确。 - Trufa
1
啊,是的,“返回(return)”这个术语确实是完全正确的! - Daniel DiPaolo
1
@Trufa 如果 eval(user_input) 的类型是整数,那么这个代码可能会起作用。 - R__raki__
解决方案:https://stackoverflow.com/a/64132078/8321339 - Vishal Gupta
30个回答

305

尝试将其转换为整数,如果失败则退出。

try:
    val = int(userInput)
except ValueError:
    print("That's not an int!")

请查看官方教程中的异常处理部分。


1
如果您只想要整数值而不是浮点数,请使用val = int(str(userInput)) - maxkoryukov
这对于布尔值也不起作用,因为 int(True) == 1int(False) == 0 - Loïc Faure-Lacroix

111

显然,这种方法对于负数不起作用,但对于正数有效。

使用isdigit()

if userinput.isdigit():
    #do stuff

61
"-1".isdigit() == False - BatchyX
1
我不这么认为,Llopis。当我回答这个问题时,我有点过早地回答了一些问题,而没有足够的知识。对于int,我会像Daniel DiPaolo的答案一样做,但是使用float()代替int()。 - jmichalicek
1
负数和浮点数返回false,因为“-”和“.”不是数字。isdigit()函数检查字符串中的每个字符是否在“0”和“9”之间。 - Carl H
2
使用 isdecimal 而不是 isdigit,因为 isdigit 是一种不安全的测试方法,它会将像 Unicode 2 的幂,² 等字符识别为数字,但无法转换为整数。 - Dave Rove

58

使用方法isnumeric()可以完成此任务:

>>>a = '123'
>>>a.isnumeric()
True

但请记住:

>>>a = '-1'
>>>a.isnumeric()
False

isnumeric()函数在字符串中所有字符都是数字字符且至少有一个字符时返回True

因此,负数不被接受。


1
值得注意的是,在Python 2.7中,这仅适用于Unicode字符串。非Unicode字符串("123456".isnumeric())会产生AttributeError: 'str' object has no attribute 'isnumeric'错误,而U"12345".numeric()则为True - perlyking
2
此外,还有一些边缘情况无法正常工作。例如 a = '\U0001f10a'a.isnumeric() 为 True,但 int(a) 会引发 ValueError 异常。 - Artyer
10
'3.3'.isnumeric() 的结果是 False - Deqing

26

对于 Python 3,下面的代码将有效。

userInput = 0
while True:
  try:
     userInput = int(input("Enter something: "))       
  except ValueError:
     print("Not an integer!")
     continue
  else:
     print("Yes an integer!")
     break 

12

编辑后: 您还可以使用以下代码来查找数字或负数

import re
num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$")
isnumber = re.match(num_format,givennumber)
if isnumber:
    print "given string is number"

您也可以根据特定要求更改格式。我有点晚看到了这篇文章,但希望它能帮助其他正在寻找答案的人:). 如果给定的代码有任何错误,请告诉我。


这将检查字符串中是否有数字(浮点数,整数等)。但是,如果除了数字之外还有其他内容,它仍将返回结果。例如:“1.2 Gbps”将返回一个错误的结果。这可能对某些人有用,也可能没有。 - Brian Bruggeman
1
另外请注意:对于现在在找的任何人,我的原始评论已经不再有效了。 :P 感谢 @karthik27 的更新! - Brian Bruggeman

9
如果你需要特定的整数或浮点数,可以尝试使用 "is not int" 或 "is not float":
user_input = ''
while user_input is not int:
    try:
        user_input = int(input('Enter a number: '))
        break
    except ValueError:
        print('Please enter a valid number: ')

print('You entered {}'.format(user_input))

如果你只需要处理整数,那么我见过的最优雅的解决方案是使用".isdigit()"方法:
a = ''
while a.isdigit() == False:
    a = input('Enter a number: ')

print('You entered {}'.format(a))

6

这个功能可以用来检查输入是否是正整数且在指定的范围内。

def checkIntValue():
    '''Works fine for check if an **input** is
   a positive Integer AND in a specific range'''
    maxValue = 20
    while True:
        try:
            intTarget = int(input('Your number ?'))
        except ValueError:
            continue
        else:
            if intTarget < 1 or intTarget > maxValue:
                continue
            else:
                return (intTarget)

5

自然数:[0, 1, 2 ... ∞]

Python 2

it_is = unicode(user_input).isnumeric()

Python 3

it_is = str(user_input).isnumeric()

整数: [-∞, .., -2, -1, 0, 1, 2, ∞]

try:
    int(user_input)
    it_is = True
except ValueError:
    it_is = False
 

浮点数: [-∞, .., -2, -1.0...1, -1, -0.0...1, 0, 0.0...1, ..., 1, 1.0...1, ..., ∞]

该内容介绍了一个包括负无穷、负数、零、正数和正无穷的浮点数范围。
try:
    float(user_input)
    it_is = True
except ValueError:
    it_is = False

2
如果您不介意的话,我想知道这个答案有什么问题。也许有更好的方法来执行这个任务,我很愿意了解。 - Luis Sieira
这并不是错的。只是人们没有理解你所陈述的条件。 - Mavaddat Javid

5

最优雅的解决方案已经提出。

a = 123
bool_a = a.isnumeric()

很遗憾,它既不能用于负整数,也不能用于一般的浮点数a。如果您的目的是检查'a'是否是超出整数范围的通用数字,我建议使用以下方法,它适用于所有类型的浮点数和整数 :). 这是测试:

def isanumber(a):

    try:
        float(repr(a))
        bool_a = True
    except:
        bool_a = False

    return bool_a


a = 1 # Integer
isanumber(a)
>>> True

a = -2.5982347892 # General float
isanumber(a)
>>> True

a = '1' # Actually a string
isanumber(a)
>>> False

1
如果转换成功,这将返回一个float而不是bool - Martin Tournoij
谢谢Carpetsmoker,你是对的 :) 已修复! - José Crespo Barrios

5
我建议在处理负数时使用 @karthik27 的方法。
import re
num_format = re.compile(r'^\-?[1-9][0-9]*\.?[0-9]*')

然后你可以使用match()、findall()等方法对这个正则表达式进行操作。


好主意。干净实用。虽然需要根据具体情况进行一些更改,但目前它也符合3.4.5。 - Jadi
为什么不直接这样写: num_format = re.compile(r'^\-?[1-9]+\.?[0-9]*') - skvalen
仅将其转换为浮点数,而不是进行其他操作。 - Giri Annamalai M

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