2011-06-24 150 views
0

我想知道最简单的方法来检查用户输入一个字母与数字。如果用户输入一个字母,它会给他们一个错误信息,并给他们提出问题。现在我拥有了,所以当用户输入'q'时,它将退出脚本。检查用户是否正在输入数字。不想字母

if station == "q": 
     break 
else: 
     #cursor.execute(u'''INSERT INTO `scan` VALUES(prefix, code_id, answer, %s, timestamp, comport)''',station) 
     print 'Thank you for checking into station: ', station 

我需要它循环回到询问电台的问题。

+0

我们谈论的命令行吗? – Bobby

+1

可能的重复[如何检查字符串是否是Python中的数字?](http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-在Python中的数字) –

+0

是命令行 –

回答

5

只是使用python内置方法

str.isdigit() 

SEE http://docs.python.org/library/stdtypes.html

例如

if station.isdigit(): 
    print 'Thank you for checking into station: ', station 
else: 
    # show your error information here 
    pass 
+0

为什么它被降低了? + 1ed –

+0

我可以举个例子。我对python很陌生。刚开始学习本周工作。 –

+0

@Anurag Uniyal:也许这是一个很容易上手的问题。 – YeJiabin

0

试试这个(使用YeJiabin的答案)

def answer(): 
    station = raw_input("Enter station number: ") 
    if not(str.isdigit(station)): 
    answer() 

没有测试过的!

+0

这适用于A-Z和特殊字符。现在怎么样零? –

+0

这有一个缺点,即用户可以通过输入大量错误的输入 – Peter

+0

@peter yeh这是事实,以最大递归深度超出错误的方式崩溃程序。这似乎是展示str.isdigit函数的一种简单方法。 – samb8s

0

有了,你想看看如果输入字符串包含数字1..9任何其他要求:

>>> import re 
>>> # create a pattern that will match any non-digit or a zero 
>>> pat = re.compile(r"[\D0]") 
>>> pat.search("12345") 
>>> pat.search("123450") 
<_sre.SRE_Match object at 0x631fa8> 
>>> pat.search("12345A") 
<_sre.SRE_Match object at 0x6313d8> 
>>> def CheckError(s): 
... if pat.search(s): 
...  print "ERROR -- contains at least one bad character." 
... 
>>> CheckError("12345") 
>>> CheckError("12a") 
ERROR -- contains at least one bad character. 
>>> CheckError("120") 
ERROR -- contains at least one bad character. 
>>> 
相关问题