如何在python中使用try和except来捕获空的用户输入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19579997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to catch empty user input using a try and except in python?
提问by Hugh Craig
I am trying to figure out how I can catch empty user input using a try and except. If you had this for example:
我想弄清楚如何使用 try 和 except 捕获空的用户输入。例如,如果你有这个:
try:
#user input here. integer input
except ValueError:
#print statement saying empty string.
Although I also need to catch another value error to make sure they entered an integer and not a character or string how could I use an if and elif setup in order to figure out if it is an empty string or str instead of int
虽然我还需要捕获另一个值错误以确保他们输入的是整数而不是字符或字符串,但我如何使用 if 和 elif 设置来确定它是空字符串还是 str 而不是 int
采纳答案by abarnert
If you literally want to raise an exception only on the empty string, you'll need to do that manually:
如果您真的只想在空字符串上引发异常,则需要手动执行此操作:
try:
user_input = input() # raw_input in Python 2.x
if not user_input:
raise ValueError('empty string')
except ValueError as e:
print(e)
But that "integer input" part of the comment makes me think what you reallywant is to raise an exception on anything other than an integer, including but not limited to the empty string.
但是评论的“整数输入”部分让我觉得你真正想要的是对整数以外的任何东西引发异常,包括但不限于空字符串。
If so, open up your interactive interpreter and see what happens when you type things like int('2')
, int('abc')
, int('')
, etc., and the answer should be pretty obvious.
如果是这样,开辟您的交互式解释,看看当你输入之类的东西会发生什么int('2')
,int('abc')
,int('')
,等等,答案应该是很明显的。
But then how do you distinguish an empty string from something different? Simple: Just do the user_input = input()
before the try
, and check whether user_input
is empty within the except
. (You put if
statements inside except
handlers all the time in real code, e.g., to distinguish an OSError
with an EINTR
errno
from one with a different errno
.)
但是你如何区分空字符串和不同的东西呢?简单:只需在user_input = input()
之前执行try
,并检查 中是否user_input
为空except
。(您在实际代码中始终将if
语句放在except
处理程序中,例如,将 anOSError
与 anEINTR
errno
与具有不同 的区分开来errno
。)
回答by fyr91
try:
input = raw_input('input: ')
if int(input):
......
except ValueError:
if not input:
raise ValueError('empty string')
else:
raise ValueError('not int')
try this, both empty string and non-int can be detected. Next time, be specific of the question.
试试这个,可以检测到空字符串和非整数。下一次,具体问题。