Py学习  »  Python

包含while循环和异常的python中的字符串

angi • 5 年前 • 1245 次点击  

嗨,我是Python编码的初学者! 这是我的代码:

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

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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38237
 
1245 次点击  
文章 [ 3 ]  |  最新文章 5 年前
HectorIX
Reply   •   1 楼
HectorIX    6 年前

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

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”时引发异常——特殊字符也需要排除在外。在这种情况下,您应该尝试使用一些正则表达式。

Ijaz Ahmad Khan
Reply   •   2 楼
Ijaz Ahmad Khan    6 年前

为了检查目的,您可以使用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'> 
JimmyCarlos
Reply   •   3 楼
JimmyCarlos    6 年前

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

if x.isdigit():
    raise Exception

还有一个.isalpha()方法用于检查字符串是否按字母顺序排列。