【问题标题】:string in python with while loop and exceptionpython中的字符串,带有while循环和异常
【发布时间】:2019-03-26 11:55:34
【问题描述】:

您好,我是 python 编码的初学者! 这是我的代码:

while True:
    try:
        x=raw_input("Please enter a word: ")
        break
    except ValueError:
        print( "Sorry it is not a word. try again")

这段代码的主要目的是检查输入。如果输入是字符串而不是 OK,但是当输入是整数时它是一个错误。我的问题是格式整数的代码也是,我没有收到错误消息。你能帮我看看错在哪里吗?

【问题讨论】:

  • raw_input 总是返回一个字符串
  • 所以我必须在代码中更具体? x=str(input("word"))
  • 例如见here。不过我不确定这是不是骗局,因为您希望以相反的方式使用此功能
  • 你使用的是哪个python版本?

标签: python string while-loop except valueerror


【解决方案1】:

如果您只需要在输入包含一位或多位数字时引发异常,那么您可以尝试:

x = str(raw_input('Please enter your message: '))

if any( i.isdigit() for i in x ):
     raise Exception("Input contains digits, therefore it is not a word")

但是,我假设您还想在输入类似于“hel$o”时引发异常——也需要排除特殊字符——。在这种情况下,您应该尝试使用一些正则表达式。

【讨论】:

    【解决方案2】:

    出于检查目的,您可以改用 input() 方法,然后做出相应决定。

    [iahmad@ijaz001 ~]$ python2.7
    Python 2.7.15 (default, May  9 2018, 11:32:33) 
    [GCC 7.3.1 20180130 (Red Hat 7.3.1-2)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 
    
    >>> x=input()
    'hi'
    >>> type(x)
    <type 'str'>
    
    >>> x=input()
    10
    >>> 
    >>> type(x)
    <type 'int'>
    >>> 
    
    [iahmad@ijaz001 ~]$ python3.6
    Python 3.6.5 (default, Apr  4 2018, 15:09:05) 
    [GCC 7.3.1 20180130 (Red Hat 7.3.1-2)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    
    >>> x=eval(input())
    'hi'
    >>> 
    >>> type(x)
    <class 'str'>
    
    >>> 
    >>> x=eval(input())
    10
    >>> 
    >>> type(x)
    <class 'int'> 
    

    【讨论】:

      【解决方案3】:

      您可以使用 .isdigit() 方法检查字符串是否仅包含数字字符,例如。

      if x.isdigit():
          raise Exception
      

      还有 .isalpha() 方法用于检查字符串是否为字母。

      【讨论】:

        猜你喜欢
        • 2013-09-21
        • 2022-01-26
        • 2012-03-09
        • 2015-03-25
        • 2023-03-14
        • 2017-03-29
        • 1970-01-01
        • 2018-01-15
        • 1970-01-01
        相关资源
        最近更新 更多