Python:测试参数是否为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4228757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Test if an argument is an integer
提问by Denis Sadowski
I want to write a python script that takes 3 parameters. The first parameter is a string, the second is an integer, and the third is also an integer.
我想编写一个带有 3 个参数的 python 脚本。第一个参数是一个字符串,第二个是一个整数,第三个也是一个整数。
I want to put conditional checks at the start to ensure that the proper number of arguments are provided, and they are the right type before proceeding.
我想在开始时进行条件检查,以确保提供正确数量的参数,并且在继续之前它们是正确的类型。
I know we can use sys.argv to get the argument list, but I don't know how to test that a parameter is an integer before assigning it to my local variable for use.
我知道我们可以使用 sys.argv 来获取参数列表,但我不知道如何在将参数分配给我的局部变量以供使用之前测试它是否为整数。
Any help would be greatly appreciated.
任何帮助将不胜感激。
采纳答案by Zeke
If you're running Python 2.7, try importing argparse. Python 3.2 will also use it, and it is the new preferred way to parse arguments.
如果您运行的是 Python 2.7,请尝试导入argparse。Python 3.2 也将使用它,它是解析参数的新首选方式。
This sample code from the Python documentation pagetakes in a list of ints and finds either the max or the sum of the numbers passed.
这个来自 Python文档页面的示例代码接受一个整数列表,并找到传递的数字的最大值或总和。
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
回答by Laurence Gonsalves
>>> int('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'foo'
Give it to int. If it doesn't raise a ValueErrorthen the string was an integer.
交给int. 如果它不引发 aValueError那么字符串是一个整数。
回答by Tony Veijalainen
Python way is to try and fail if the input does not support operation like
Python 的方法是尝试失败,如果输入不支持像这样的操作
try:
sys.argv = sys.argv[:1]+map(int,sys.argv[1:])
except:
print 'Incorrect integers', sys.argv[1:]
回答by John Giotta
You can cast the argument and try... except the ValueError.
您可以转换参数并尝试...除了 ValueError。
If you are using sys.argv, also investigate argparse.
如果您正在使用 sys.argv,还要调查 argparse。
回答by wkl
str.isdigit()can be used to test if a string is comprised solely of numbers.
str.isdigit()可用于测试字符串是否仅由数字组成。
回答by Zack
You can use type to determine the type of any object in Python. This works in Python 2.6, I don't personally know if it's present in other versions.
您可以使用 type 来确定 Python 中任何对象的类型。这适用于 Python 2.6,我个人不知道它是否存在于其他版本中。
obvious_string = "This is a string."
if type(obvious_string) != int:
print "Bro, that is so _not_ an integer."
else:
print "Thanks for the integer, brotato chip."
回答by Matthew Schinckel
More generally, you can use isinstanceto see if something is an instance of a class.
更一般地,您可以使用isinstance来查看某物是否是类的实例。
Obviously, in the case of script arguments, everything is a string, but if you are receiving arguments to a function/method and want to check them, you can use:
显然,在脚本参数的情况下,一切都是字符串,但是如果您正在接收函数/方法的参数并想要检查它们,您可以使用:
def foo(bar):
if not isinstance(bar, int):
bar = int(bar)
# continue processing...
You can also pass a tuple of classes to isinstance:
您还可以将一组类传递给 isinstance:
isinstance(bar, (int, float, decimal.Decimal))
回答by Matthew Schinckel
I am new to Python so I am posting this not only to help but also be helped: get comments on why my approach is/isn't the the best one, that is.
我是 Python 的新手,所以我发布这篇文章不仅是为了帮助,而且是为了帮助:就为什么我的方法是/不是最好的方法发表评论,也就是说。
So, with the disclaimer that I am not an experienced python dev, here is what I would do:
因此,免责声明我不是经验丰富的 python 开发人员,这是我会做的:
inp = sys.argv[x]
try:
input = int(inp)
except ValueError:
print("Input is not an integer")
What the above does is that it puts sys.argv[x] to inp and then tries to put the integer form of inp to input. If there is not an integer form of inp then inp is not a number so a ValueError exception is raised.
上面所做的是将 sys.argv[x] 放入 inp,然后尝试将 inp 的整数形式放入输入。如果 inp 没有整数形式,则 inp 不是数字,因此会引发 ValueError 异常。
I take it that's your main problem and you know how to check if you have all three parameters in the correct form. If not, just let us know and I am sure you will get more answers. :)
我认为这是您的主要问题,您知道如何检查所有三个参数的格式是否正确。如果没有,请告诉我们,我相信您会得到更多答案。:)
Just realized Tony Veijalainenposted a similar answer

