区分字符串和字符串表示

时间:2015-08-03 19:41:40

标签: python string python-3.x

Python 3.4

我正在编写验证函数来检查用户的输入。在一种情况下,我试图验证用户输入的0到99之间的整数。

所有内容都以字符串形式出现,因此假设我们有一个整数的字符串表示,显而易见的起点是:

isinstance(int(userinput), int)

但假设用户犯错误的方式没有尽头,假设他或她偶然输入'2l'。这实际上是一个字符串,而不是整数的字符串表示。上述isinstance()检查结果为:

ValueError: invalid literal for int() with base 10: '2l'

我无法弄清楚如何解释这种可能性。

2 个答案:

答案 0 :(得分:5)

使用tryexcept,您甚至不需要isinstance检查:

userinput = None
try:
    userinput = int(input("type a number"))
except ValueError:
    print ("invalid input")

if userinput is not None:
     # rest of code

答案 1 :(得分:0)

您可以使用正则表达式检查任意语法。对于一系列数字:

import re

match = re.search('\d+', userinput)
if match:
    print int(match.group(0))
相关问题