Python: 测试参数是否为整数
我想写一个Python脚本,这个脚本需要接收三个参数。第一个参数是一个字符串,第二个参数是一个整数,第三个参数也是一个整数。
我想在开始的时候加一些条件检查,确保提供的参数数量正确,并且类型也对,这样才能继续执行。
我知道可以用sys.argv来获取参数列表,但我不知道怎么在把参数赋值给我的本地变量之前,检查一下这个参数是不是整数。
任何帮助都会非常感谢。
8 个回答
11
更一般来说,你可以用 isinstance
来检查某个东西是不是某个类的实例。
显然,在脚本参数的情况下,所有东西都是字符串,但如果你在接收函数或方法的参数,并想要检查它们的类型,可以使用:
def foo(bar):
if not isinstance(bar, int):
bar = int(bar)
# continue processing...
你还可以把多个类放在一个元组里,传给 isinstance:
isinstance(bar, (int, float, decimal.Decimal))
20
str.isdigit()
可以用来检查一个字符串是否完全由数字组成。
9
如果你在使用 Python 2.7,可以试着导入 argparse 这个模块。Python 3.2 也会用到它,而且这是现在推荐的处理参数的方式。
下面这段代码来自 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))