Thanks to those who give me a solution earlier on. However i need to utilise the split function for the solution as its part of the requirement stated. When i run this code, there is an error
TypeError Traceback (most recent call last) in 7 8 for x in dob_list: ----> 9 age =[year-int(x.split("-")[-1:])] 10 print(age)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
dob_list = ['01-Jan-1990', '11-Aug-1995', '15-Apr-1982', '20-Mar-1988', '25-Nov-1976', '07-Dec-1965',
'18-Dec-1977', '25-May-1994', '09-Oct-1981', '19-Feb-1981']
year = 2021
age =[]
dob = []
for x in dob_list:
age =[year-int(x.split("-")[-1:])]
print(age)
CodePudding user response:
x.split("-")[-1:]
actually gives you a list which contains only the last list item, since you are using a range (like [-1:]
) instead of a number (like [-1]
).
x.split("-")[-1]
gives you the last list item (from x.split("-")
) as a string.
CodePudding user response:
The number one debug tool in python is print
. A line is failing? Print the stuff on the line before to see what you get.
dob_list = ['01-Jan-1990', '11-Aug-1995', '15-Apr-1982', '20-Mar-1988', '25-Nov-1976', '07-Dec-1965',
'18-Dec-1977', '25-May-1994', '09-Oct-1981', '19-Feb-1981']
year = 2021
age =[]
dob = []
for x in dob_list:
print("next value", repr(x.split("-")[-1:]))
age =[year-int(x.split("-")[-1:])]
Running, I get
$ python3 test.py
next value ['1990']
Traceback (most recent call last):
File "/home/td/tmp/j/i.py", line 12, in <module>
age =[year-int(x.split("-")[-1:])]
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
That traceback is useful. I see the failing line and it tells me int()
doesn't like lists. Looking backwards... yep, that was a list being passed in. Just get the final value instead.
age =[year-int(x.split("-")[-1])]