Search code examples
pythonpython-3.xlistpython-datetime

TypeError: unsupported operand type(s) for -: 'str' and 'int' [Python]


Why does this error keep showing up? I am just trying to create a table. The code for this is below:

import datetime


q= datetime.date(2004,12,25)

e= datetime.date(2019,11,23) 

f= datetime.date(2019,11,26)

p= datetime.date(2004,12,13)

nam=[["attack on titan",10,"completed",p,q],["one punch man",10,"WATCHING",e,f]]

print("|         NAME           | SCORE |   STATUS   |  DATE STARTED  |    DATE ENDED   |") 

for KI in nam:
  print("|",KI[0]," "*22-len(KI[0]),"|"," ",KI[1]," ","|",KI[2]," "*(10-len(KI[2])),"|",""*2,KI[3], 
         " "*2,"|"," "*3,KI[4]," "*2,"|")

Don't give too much attention to the space multiplication.

Error:

|         NAME           | SCORE |   STATUS   |  DATE STARTED  |    DATE ENDED   |


Traceback (most recent call last):


    line 9, in <module>

    print("|",KI[0]," "*22-len(KI[0]),"|"," ",KI[1]," ","|",KI[2]," "*(10-len(KI[2])),"|"," "*2,KI[3]," "*2,"|"," "*3,KI[4]," "*2,"|")


TypeError: unsupported operand type(s) for -: 'str' and 'int'
.........................................................................................               

Solution

  • The error is occurring with " "*22-len(KI[0]).
    " "*22 is a string consisting of 22 spaces and len(KI[0]) is an integer.
    As the TypeError is telling you, subtracting an integer from a string doesn't make sense.
    I'm guessing you're intention is " "*(22-len(KI[0])).