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

Tru*_*ufa 125 python types input

如何检查,如果用户的字符串输入是一个数字(例如-1,0,1等)?

user_input = input("Enter something:")

if type(user_input) == int:
    print("Is a number")
else:
    print("Not a number")
Run Code Online (Sandbox Code Playgroud)

由于input始终返回字符串,因此上述操作无效.

Dan*_*olo 236

只需尝试将其转换为int,然后如果它不起作用则挽救.

try:
   val = int(userInput)
except ValueError:
   print("That's not an int!")
Run Code Online (Sandbox Code Playgroud)

  • 这使您可以接受4.1等技术上只有4有效的东西.像这样发生秘密转换也违背了python的心态,我宁愿在我的公共界面上进行严格的检查 (12认同)
  • @PeterR你可以使用`float()`而不是`int()` (2认同)
  • 这个不用于检查值是布尔值还是整数,布尔值被认为是0或1. (2认同)
  • @PeterR 不确定“这让您可以接受 4.1 之类的东西”是什么意思。DiPaolo 的代码在字符串输入 4.1 上抛出 ValueError (2认同)

jmi*_*cek 68

显然这对负面价值不起作用,但它会是积极的.对此感到抱歉,几个小时前我刚刚了解了这一点,因为我刚刚进入Python.

使用isdigit()

if userinput.isdigit():
    #do stuff
Run Code Online (Sandbox Code Playgroud)

  • "-1".isdigit()== False (43认同)
  • 使用“isdecimal”而不是“isdigit”,因为“isdigit”是一种不安全的测试,它将 unicode 2 的幂、 ² 等字符识别为无法转换为整数的数字。 (2认同)

And*_*dez 33

我认为你在这里寻找的是方法isnumeric()(python3.x的文档):

>>>a = '123'
>>>a.isnumeric()
true
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助

  • `'3.3'.isnumeric()`是'False` (6认同)
  • 此外,在某些极端情况下这不起作用。取 `a = '\U0001f10a'`。`a.isnumeric()` 为 True,但 `int(a)` 引发 ValueError。 (2认同)

Raz*_*orX 19

对于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 
Run Code Online (Sandbox Code Playgroud)


kar*_*k27 11

编辑:您也可以使用下面的代码来查明它是一个数字还是一个负数

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"
Run Code Online (Sandbox Code Playgroud)

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

  • 另请注意:对于现在正在查看的任何人,我原来的评论不再有效。:P 感谢@karthik27 的更新! (2认同)

Woo*_*ody 8

如果您特别需要int或float,可以尝试"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(a))
Run Code Online (Sandbox Code Playgroud)

如果你只需要使用整数,那么我见过的最优雅的解决方案是".isdigit()"方法:

a = ''
while a.isdigit() == False:
    a = input('Enter a number: ')

print('You entered {}'.format(a))
Run Code Online (Sandbox Code Playgroud)


小智 5

如果输入是一个正整数并且在特定范围内,则可以正常检查

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)
Run Code Online (Sandbox Code Playgroud)


rac*_*rma 5

对于负数,我会推荐这个,@ karthik27

import re
num_format = re.compile(r'^\-?[1-9][0-9]*\.?[0-9]*')
Run Code Online (Sandbox Code Playgroud)

然后用正则表达式,match(),findall()等做任何你想做的事情


Jos*_*ios 5

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

a=123
bool_a = a.isnumeric()
Run Code Online (Sandbox Code Playgroud)

不幸的是,它对于负整数和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
Run Code Online (Sandbox Code Playgroud)

希望对你有帮助 :)


Lui*_*ira 5

自然:[0, 1, 2 ... ?]

蟒蛇 2

it_is = unicode(user_input).isnumeric()
Run Code Online (Sandbox Code Playgroud)

蟒蛇 3

it_is = str(user_input).isnumeric()
Run Code Online (Sandbox Code Playgroud)

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

try:
    int(user_input)
    it_is = True
except ValueError:
    it_is = False
 
Run Code Online (Sandbox Code Playgroud)

浮动: [-?, .., -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
Run Code Online (Sandbox Code Playgroud)

  • 如果您不介意,我想知道这个答案有什么问题。可能有更好的方法来执行我愿意知道的这项任务 (2认同)