Python未用前导零却出现‘Leading 0 not permitted’错误的原因与解决
日期验证程序的前导零语法错误问题
我编写了一段日期验证程序,代码如下:
from dateutil.parser import parse import re from datetime import datetime def date_fun(date): try: dt = parse(date) dt = dt.strftime('%d/%m/%Y') dmy_split=re.split('[- / ]', dt) # error here: if (eval(dmy_split[0])>=1 and eval(dmy_split[0])<=12 and eval(dmy_split[1])>=1 and eval(dmy_split[1])<=12 or len(dmy_split[2])==2): print("ambiguous") # Format matched else: print("True") except ValueError: # If match not found keep searching print("False") date_fun("abc") date_fun("12/1/91") date_fun("2002-9-18")
运行时,在标注的条件判断代码处出现Leading 0 not permitted错误,错误信息如下:
if (eval(dmy_split[0])>=1 and eval(dmy_split[0])<=12 and eval(dmy_split[1])>=1 and eval(dmy_split[1])<=12 or len(dmy_split[2])==2): File "<string>", line 1 01 ^ SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
我并未手动使用类似“01”的前导零,请问该错误产生的原因是什么?如何解决?
错误原因
你用strftime('%d/%m/%Y')格式化日期时,%d和%m会将日、月格式化为两位数字,比如1号会变成01,9月会变成09。这些带前导零的字符串被dmy_split拆分出来后,用eval()转换时,Python 3会把"01"当成非法的十进制整数(无前缀的前导零在Python 3中不允许,过去Python 2会默认解析为八进制,但Python 3取消了这个行为),因此抛出语法错误。
解决方法
完全没必要用eval()来转换字符串为整数,直接用int()函数即可——int()会自动忽略字符串中的前导零,正确解析为十进制整数。修改条件判断中的所有eval()为int():
修改后的核心代码:
# 替换原条件判断中的eval为int if (int(dmy_split[0])>=1 and int(dmy_split[0])<=12 and int(dmy_split[1])>=1 and int(dmy_split[1])<=12 or len(dmy_split[2])==2):
另外,建议优化拆分逻辑:因为你已经用strftime把日期格式化为%d/%m/%Y,分隔符固定是/,没必要用正则拆分,直接用dt.split('/')更高效:
dmy_split = dt.split('/')
内容的提问来源于stack exchange,提问作者Laxmi Ty
相关产品推荐
相关产品推荐

