我試圖做一個程序,它接受一個字符串,表示日期,從列表,並將其與另外兩個日期。如果在這兩個日期之間,程序會將日期,月份和年份中的字符串替換爲分隔的字符串。值誤差將字符串轉換爲int Python中
的問題是,如果我這個字符串轉換爲「廉政」,在控制檯也沒關係,但是當我運行該程序,我有以下錯誤:
ValueError: invalid literal for int() with base 10: ''
這是我的代碼:
def date(lst, d1, d2):
for d in lst:
if int(d[4:])>=int(d1[4:]) or int(d[4:])<=int(d2[4:]):
if int(d[2:4])>=int(d1[2:4]) or int(d[2:4])<=int(d2[2:4]):
if int(d[0:2])>=int(d1[0:2]) or int(d[0:2])<=int(d2[0:2]):
j=d
j1=j[0:2]
j2=j[2:4]
j3=j[4:]
lst.insert(lst.index(d),j3)
lst.insert(lst.index(d),j2)
lst.insert(lst.index(d),j1)
lst.remove(d)
return lst
所以,
print date(['24012014', '22032015', '03022015', '15122014', '11112015'], '22022014', '10112015')
應該返回['24012014', 22, 3, 2015, 3, 2, 2015, 15, 12, 2014, '11112015']
Yikes - 當您嘗試穿過它時不要更改列表。創建一個新列表並返回。 – doctorlove
我會,但這是學校,我必須使用相同的列表.... – PadreMaronno
如果日期是相反的順序,例如'20141225',你可以比較它們而不將它們轉換爲'int' – Pynchia