簡體   English   中英

如何使用日期時間庫驗證 python 中的字符串輸入並不斷提示用戶輸入直到有效輸入?

[英]How to validate a string input in python using datetime library and keep prompting user for input until valid input?

我試過使用這個過程:

import datetime
date_string = input()
format = "%Y-%m-%d"

try:
    datetime.datetime.strptime(date_string, format)
    print("This is the correct date string format.")
except ValueError:
    print("This is the incorrect date string format. It should be YYYY-MM-DD")

當我用“2021-3-3”填充 date_string 的輸入時,output 是

This is the correct date string format.

但是當我對“2021-03-03”做一點改動時,output 是

This is the incorrect date string format. It should be YYYY-MM-DD

我如何使第二個輸入為真。 所以,當我輸入“2021-03-03”時,output 也將是

This is the correct date string format.

我也想知道如何提示用戶,直到他輸入正確的格式,這樣當他輸入錯誤的格式或值時,output 是

This is the incorrect date string format, try again fill the

並且,程序不斷提示用戶輸入

此代碼適用於我的機器,如果不成功,它會提示用戶再次輸入。

import datetime
format = "%Y-%m-%d"

while(True):
    date_string = input("> ").strip()
    try:
        datetime.datetime.strptime(date_string, format)
        print("This is the correct date string format.")
        break
    except ValueError:
        print("This is the incorrect date string format. It should be YYYY-MM-DD")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM