Python从int(input())异常中检索字符串输入

时间:2014-06-19 14:24:19

标签: python python-3.x

我尝试使以下代码正常工作:

try:
    x = int(input())
except ValueError as var:
    #print the input of the user

如果我尝试print(var),它将打印错误行而不是用户的原始输入 例如,如果用户要插入bla而不是整数,我想打印bla

P.S我不能改变行x = int(input()),否则我会轻易解决它

3 个答案:

答案 0 :(得分:1)

打印var时会出现什么? 在您提供该信息之前,这是一个可能的hackish解决方案:

try:
    x = int(input())
except NameError as var:
    e = str(var)
    print e[6:-16]

假设var等于

NameError: name 'user_input' is not defined

其中user_input是用户的输入。

编辑:这篇文章假设代码在Python 2.x中运行,而它似乎在运行Python 3。如果人们想知道Python 2的话就把它留下来

答案 1 :(得分:1)

我会改变x = int(input())行,但既然你问,这是一个丑陋的黑客利用ValueError消息的格式:

invalid literal for int() with base 10: 'foobar'

首先将其拆分为:并删除周围的'

try:
    x = int(input())
except ValueError as e:
    original_input = str(e).split(":")[1].strip()[1:-1]
    print(original_input)

顺便说一下,如果您仍在使用Python 2.x,则应使用raw_input代替input 。事实上,如果可能,旧的input会自动尝试转换为int

try:
    x = int(raw_input())
except ValueError as e:
    original_input = str(e).split(":")[1].strip()[1:-1]
    print original_input

答案 2 :(得分:0)

这是从传递的错误消息中读取输入的hack。它正确处理输入字符串和反斜杠中的引号。

#We get input from the user
try:
    x = int(input())
except ValueError as var:
    #we need to find the text between the quotes in the error message
    #but we don't know what kind of quote it will be. We will look for
    #the first quote which will be the kind of quotes.

    #get the location or existence of each kind of quote
    first_dquote = str(var).find('"')
    first_squote = str(var).find("'")

    used_quote = 0
    #if double quotes don't exist then it must be a single quote
    if -1 == first_dquote:
        used_quote = first_squote
    #if single quotes don't exist then it must be a dubble quote
    elif -1 == first_squote:
        used_quote = first_dquote
    #if they both exist then the first one is the outside quote
    else: used_quote = min(first_squote,first_dquote)

    #the output is what is between the quotes. We leave of the end
    #because there is the end quote.
    output = str(var)[used_quote+1:-1]

    #but the error message is escaped so we need to unescape it
    output = bytes(output,"utf_8").decode("unicode_escape")

    #print the output
    print(output)