gpt4 book ai didi

python - 检查字符串的格式/内容

转载 作者:太空宇宙 更新时间:2023-11-04 07:40:47 25 4
gpt4 key购买 nike

此程序旨在要求日期为 dd/mm/yyyy。然后它应该检查用户是否以正确的格式(dd/mm/yyyy)输入了日期。我的程序无法正确识别格式。这是我的程序:

date = (input("enter the date as dd/mm/yyyy: "))
date = day, month, year = date.split("/")
if date == (day + '/' + month + '/' + year):
print (date)
if len(day) == 1 or len(day) == 2:
print("1")
if len(month) == 1 or len(month) == 2:
print("2")
if len(year) == 4:
print ("3")
else:
if len(day) == 1 or len(day) == 2:
print("4")
if len(month) == 1 or len(month) == 2:
print("5")
if len(year) == 4:
print ("6")

目前正在打印的数字除了检查日期的有效性外没有其他目的。到目前为止,只打印了 4、5 和 6,这意味着我的程序无法识别日期格式。

最佳答案

您的解决方案不起作用,因为 date=day, month, year = date.split("/")date 设置为 list,然后将它与 string(day + '/' + month + '/' + year)进行比较。但是,您的解决方案是已解决的问题,请改为:

import datetime
date = (input("enter the date as dd/mm/yyyy: "))

try: datetime.datetime.strptime(date,"%d/%m/%Y")
except ValueError: # incorrect format

此外,您以后可能会将其转换为 datetime 对象,因此您可以在 try block 中这样做!

作为进一步的优化,请注意许多用户不想使用 / 作为 datesep 输入他们的日期!对您的输入进行一些反省,并适当调整您的 datesep。

date = input("enter the date: ")

if "-" in date: datesep = "-"
elif "/" in date: datesep = "/"
elif "." in date: datesep = "."
else: datesep = ""

if len(date) < 6: yeartype = "%y"
elif date[-4:-2] not in ("19","20"): yeartype = "%y"
else: yeartype = "%Y"

try: date = datetime.datetime.strptime(date,"%d{0}%m{0}{1}".format(datesep,yeartype))
except ValueError: # invalid date

现在您的代码将以 2014 年 2 月 2 日的有效 datetime 对象结束:

  • 02022014
  • 222014
  • 0222014
  • 222014
  • 020214
  • 02214
  • 2214
  • 2014 年 2 月 2 日
  • 2014 年 2 月 2 日
  • 2-2-14
  • 2/2/2014
  • 2/2/14
  • 等等等等

关于python - 检查字符串的格式/内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21791143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com