如何检查用户是否将“输入"或“原始输入"提示留空? [英] How do I check if a user left the 'input' or 'raw_input' prompt empty?

查看:39
本文介绍了如何检查用户是否将“输入"或“原始输入"提示留空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查是否输入了内容?

How do I check if input has been entered?

例如:

x = str(raw_input('Message>> '))

y = input('Number>> ')

推荐答案

您知道第二个是否没有输入任何内容,因为它会引发 SyntaxError.您可以像这样捕获错误:

You know if nothing was entered for the second one because it will raise a SyntaxError. You can catch the error like this:

try:
    y=input('Number>> ')
except SyntaxError:
    y = None

然后测试

# not just 'if y:' because 0 evaluates to False!
if y is None:

或者,最好使用 raw_input:

try:
    y = int(raw_input('Number>> '))
except ValueError:
    print "That wasn't a number!"

对于第一个,如果没有输入,x 将是一个空字符串.对 str 的调用是不必要的——raw_input 已经返回一个字符串.可以显式测试空字符串:

For the first one, x will be an empty string if nothing is entered. The call to str is unnecessary -- raw_input already returns a string. Empty strings can be tested for explicitly:

if x == '':

或隐式:

if x:

因为唯一的 False 字符串是一个空字符串.

because the only False string is an empty string.

这篇关于如何检查用户是否将“输入"或“原始输入"提示留空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆