elif search.lower() == "m":
DMY = input("please enter your date of birth you are looking for (date/month/year) : ")
DMY = DMY.split("/")
DMY = DMY[1]
for line in open("datafile.txt"):
if DMY in line:
print(line)
答案 0 :(得分:6)
您可以使用异常处理:
DMY = input("please enter your date of birth you are looking for (date/month/year) :` ")
DMY = DMY.split("/", 2)
try:
DMY = int(DMY[1])
except (IndexError, ValueError):
# User did not use (enough) slashes or the middle value was not an integer
print("Oops, did you put in an actual date?")
或者您可以尝试解析日期:
import datetime
DMY = input("please enter your date of birth you are looking for (date/month/year) :` ")
try:
DMY = datetime.datetime.strptime(DMY, '%d/%m/%Y').date()
except ValueError:
# User entered something that doesn't fit the pattern dd/mm/yyyy
print("Oops, did you put in an actual date?")
后者的优势在于您现在拥有一个实际的datetime.date()
对象,这不仅仅是检查用户是否输入了斜杠和整数;它还验证输入的值实际上可以解释为日期。 30/02/4321
不会解析,因为即使在4321年,也没有2月30日。
答案 1 :(得分:1)
使用find:
s = "29/01/2014"
if s.find("/") == -1:
print "No '/' here!"
else:
print "Found '/' in the string."