Date=int(input())
我希望该用户只能输入8个字符。然后,我要转换成最新的日期。
答案 0 :(得分:1)
通常使用while循环处理输入,以保持请求直到给出有效输入为止。像这样:
MAX_ATTEMPTS = 3
current_attempt = 0
while current_attempt < MAX_ATTEMPTS:
date = input('Please enter the date as ddmmyyyy')
if len(date) == 8 and date.isdigit():
break
current_attempt += 1
else:
raise RuntimeError('Incorrect date format provided 3 times.')
答案 1 :(得分:1)
就像c中的getch一样,似乎有一个包装该功能的模块。 getch module可以满足您的要求。
import getch
# ...
char = getch.getch() # User input, but not displayed on the screen
# or
char = getch.getche() # also displayed on the screen
您可以循环获取8个字符
st=""
for i in range(8):
st+ getch.getche()
答案 2 :(得分:0)
from datetime import datetime
while True:
userInput = str(input('Enter date as YYYYMMDD:'))
try:
date = datetime.strptime(userInput, '%Y%m%d').date()
print(date)
except ValueError:
print("Incorrect format")
无限循环以读取用户输入并从中创建日期。
如果用户输入的字符少于或超过8个字符或当天无效,则引发“ ValueError”。