如何知道用户是否使用Python按Enter键

use*_*284 6 python

如何知道用户是否Enter使用过Python?

例如 :

user = raw_input("type in enter")
if user == "enter":
    print "you pressed enter"
else:
    print "you haven't pressed enter"
Run Code Online (Sandbox Code Playgroud)

jul*_*enc 12

正如@jonrsharpe所说,正确退出该raw_input功能的唯一方法是按Enter键.因此,解决方案是检查结果是否包含某些内容:

text = raw_input("type in enter")
if text == "":
    print "you pressed enter"
else:
    print "you typed some text before pressing enter"
Run Code Online (Sandbox Code Playgroud)

我看到退出该raw_input函数的唯一其他方法将抛出异常,例如:

  • EOFError 如果你输入 ^D
  • KeyboardInterrupt 如果你输入 ^C
  • ...

  • @jeppoo1你是对的,我在 2014 年写了这篇文章,当时 python2 仍然很流行:)我刚刚更新了我的答案以符合 python3! (2认同)