对于 Python 3,我正在使用这个函数:
def user_prompt(question: str) -> bool:
""" Prompt the yes/no-*question* to the user. """
from distutils.util import strtobool
while True:
user_input = input(question + " [y/n]: ")
try:
return bool(strtobool(user_input))
except ValueError:
print("Please use y/n or yes/no.\n")
strtobool() 函数将字符串转换为布尔值。如果无法解析字符串,则会引发 ValueError。
在 Python 3 中,raw_input() 已重命名为 input()。
正如 Geoff 所说,strtobool 实际上返回 0 或 1,因此必须将结果强制转换为 bool。
这是strtobool的实现,如果你想让特殊的词被识别为true,你可以复制代码并添加你自己的案例。
def strtobool (val):
"""Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
val = val.lower()
if val in ('y', 'yes', 't', 'true', 'on', '1'):
return 1
elif val in ('n', 'no', 'f', 'false', 'off', '0'):
return 0
else:
raise ValueError("invalid truth value %r" % (val,))