【问题标题】:validating a string using try except in python在 python 中使用 try 验证字符串
【发布时间】:2015-07-12 15:50:49
【问题描述】:

我一直在尝试让这段代码工作:

    last_bits_repeat= "yes"
    while last_bits_repeat== "yes":
        try:
            another_number_repeat= input("do you have another number to add??")
            another_number_repeat= str(another_number_repeat)
        except TypeError as e:
            if not repeat:
                print("You left this empty, please write something!")   
                last_bits_repeat= "yes"
            else:
                print("This is not empty, but invalid")

它不起作用,我认为是因为TypeError

我的问题是我应该使用哪个异常来验证字符串?用户应输入“是”或“否”。

【问题讨论】:

标签: python try-except


【解决方案1】:

它不起作用,我认为是因为 TypeError。

如果这是 python2(带有from __future__ import print_function),它不起作用,因为input 没有按照您的预期执行 - 即它没有将输入的值分配给another_number_repeat 变量使用@ 987654321@ 代替。

在python3中,输入就好了,但不会引发异常。

我的问题是我应该使用哪个异常来验证字符串? (another_number_repeat) 如果可以的话。

您不需要例外。试试这个:

def get_choice(prompt, choices):
    valid = False
    while not valid:
        answer = raw_input(prompt).strip()
        valid = answer in choices
    return answer

answer = get_choice('do you have another number to add?', ['yes', 'no'])

我之前已将此代码用于整数,因此我认为它应该适用于正确的异常。

如果您想对任意输入(数字、文本、选项)使用相同的代码,正则表达式有助于避免繁琐的异常检查,并保持代码流畅:

import re
def get_input(prompt, regexp, convert=str):
    valid = False
    while not valid:
        answer = raw_input(prompt).strip()
        valid = re.match(regexp, answer)
    return convert(answer)

get_input('add a number? (yes or no)', r'(yes)|(no)')
get_input('number?', r'^[0-9]*$', int)

【讨论】:

  • 这是 python3 - 注意print() - 所以input 是正确的
  • @NightShadeQueen 如果这是 python3,为什么要使用 str(another_number_repeat) 之类的东西?
  • 因为他或她很困惑。另一方面,他或她没有收到语法错误,这意味着print() 可能是正确的。
  • 在 Python 2 中您也不会收到 print("You left this empty, please write something!") 的语法错误。虽然我猜你是对的,但代码可能是 python 3。
  • 它的python 3,我使用str(another_number_repeat)只是因为我之前的验证(验证整数)在我执行new_number= int(input("give me a number")时不起作用,但在我执行new_number= input("Give me a number")然后@987654336时起作用@。很抱歉造成混乱!
【解决方案2】:

我通常在这些异常“弄清楚”问题中做什么:

  1. 删除整个 try: except: 子句
  2. 运行脚本并产生无效数据
  3. 查看将打印异常名称的错误消息 如果您期望多个错误类型,请为每个测试用例运行测试用例: --空白条目(用户点击的地方) --用户输入八进制代码等
  4. 重新创建 try: except: ,从步骤 #3 中指定异常名称

找出异常代码的示例代码:

    last_bits_repeat= "yes"
    while last_bits_repeat== "yes":

            another_number_repeat= input("do you have another number to add??")
            another_number_repeat= str(another_number_repeat)

【讨论】:

    猜你喜欢
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-15
    • 2013-05-09
    • 2012-07-02
    • 1970-01-01
    相关资源
    最近更新 更多