2014-10-11 99 views
0

对不起,我是初学者。但是,像如果我有:测试输入是字符串而不是数字吗?

x = eval(input('Enter a value for x: ')) 

怎样让这个如果人输入一个字符串,而不是数字,将打印"Enter a number"而不是让错误的。某些类型的if语句,其中:

if x == str(): 
    print('Please enter a number') 

else: 
    print('blah blah blah') 
+0

更好地贴近目标将是:我如何检查是否一个字符串是Python中的号码是多少?(http://stackoverflow.com/questions/354038/how-do-i - 检查,如果一个字符串是一个数字在python)或 [你如何检查一个字符串是否只包含数字 - 蟒蛇](http://stackoverflow.com/questions/21388541/how- DO-您检查-IF-A-字符串包含专用号码的Python) – bummi 2014-10-11 22:30:16

回答

0

这听起来像你正在寻找str.isdigit

>>> x = input(':') 
:abcd 
>>> x.isdigit() # Returns False because x contains non-digit characters 
False 
>>> x= input(':') 
:123 
>>> x.isdigit() # Returns True because x contains only digits 
True 
>>> 

在你的代码,这将是:

if not x.isdigit(): 
    print('Please enter a number') 
else: 
    print('blah blah blah') 

在一个注意,你应该避免使用eval(input(...)),因为它可以用来执行任意表达式。换句话说,它通常是一个安全漏洞,因此被大多数Python程序员认为是不好的做法。参考:

Is using eval in Python a bad practice?

相关问题