基本上我正在做一個 python 代碼,其中完整的日期以 DD-YY-MM 格式的字串輸入,然后分別輸出日、月和年。我需要驗證輸入的日期,以便滿足以下條件:
- 日期不低于 1 或超過 31
- 月份在 1 到 12 的范圍內
- 年份不少于 1900
FullDate=input("enter todays date")
D=FullDate[0:2]
M=FullDate[3:5]
Y=FullDate[6:10]
if D>31 and D<1:
print ("invalid date")
else:
print("the date is",D)
if M<1 and M>12:
print("invalid month")
else:
print("the date is",M)
if Y<1990:
print ("invalid year")
else:
print("the year is",Y)
這是我嘗試過的,但是由于日期是作為字串輸入的,因此我不能在 if 條件中使用 > 和 < 并且當我這樣做時出現錯誤:
型別錯誤:“str”和“int”的實體之間不支持“>”
如何在將輸入作為字串的同時設定這些條件?
uj5u.com熱心網友回復:
您必須將字串顯式轉換為 int :
import sys
FullDate=input("enter todays date")
D=FullDate[0:2]
M=FullDate[3:5]
Y=FullDate[6:10]
if int(D)>31 or int(D)<1:
sys.exit("invalid day")
else:
print("the day is",D)
if int(M)<1 or int(M)>12:
sys.exit("invalid month")
else:
print("the month is",M)
if int(Y)<1990:
sys.exit("invalid year")
else:
print("the year is",Y)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/492583.html
上一篇:str_extract所有語法
下一篇:gsub洗掉轉義字串
