简体   繁体   中英

Why my python code think i was trying to concatenate <int> to <str> while actually i wasn't?

I was trying to create a function timeConversion that take 12-hour time format as an input and return 24-hour time format. The input is a string containing time in 12-hour format ie hh:mm:ssAM , hh:mm:ssPM . The hh , mm , ss represent hour, minute, and second respectively.

The full code:

def timeConversion(s):
     s = list(s)
     if s[-2:] == 'AM':  
        if s[:2] == ['1', '2']:
            s[0] = 0
            s[1] = 0
     else  :
        if s[:2] != ['1', '2']:
            s[0] = (int(s[0])*10 + int(s[1]) + 12) // 10
            s[1] = (int(s[0]+s[1]) + 12) % 10
        
      del s[-2:]
      s = ''.join(s)
      return s

x = timeConversion("07:05:45PM")
x

In line 10

s[1] = (int(s[0]+s[1]) + 12) % 10

I got the following error message:

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

I tried using

type(int(s[0]+s[1]))

and it return int type, so what did I miss?

In the line

s[1] = (int(s[0]+s[1]) + 12) % 10

You converted int(s[0]+s[1]). If s[0] = '1' and s[1] = '2', then it will give 12. But you need 3. So replace the line 10 with the following line..

s[1] = (int(s[0])+int(s[1]) + 12) % 10

Maybe your list s contains strings, therefore

s[0]+s[1]

causes the problem. Try

int(s[0]) + int(s[1])

I see your problem.

int(c[0]+c[1])

not equals to

int(s[0]) + int(s[1])

In these two lines,

s[0] = (int(s[0])*10 + int(s[1]) + 12) // 10
s[1] = (int(s[0]+s[1]) + 12) % 10

the result is int which is causing the problem.

def timeConversion(s):
    s = list(s)
    if s[-2:] == 'AM':  
        if s[:2] == ['1', '2']:
            s[0] = 0
            s[1] = 0
    else:
        if s[:2] != ['1', '2']:
            # change the evaluated result to str
            s[0] = str((int(s[0])*10 + int(s[1]) + 12) // 10)
            s[1] = str((int(s[0]+s[1]) + 12) % 10)
        
    del s[-2:]
    s = ''.join(s)
    return s
>>> x = timeConversion("07:05:45PM")
>>> x
'19:05:45'

After reading the solutions and comments i've noticed my mistakes. Allow me to provide my own solution to the problems. This solution required me to introduce an extra variable(which i try to avoid before, but failed miserably).

def timeConversion(s):
    s = list(s)
    if s[-2:] == ['A','M']:  
        if s[:2] == ['1', '2']:
            s[0] = 0
            s[1] = 0
    else  :
        if s[:2] != ['1', '2']:
            #introducing variable k
            k = int(s[0]+s[1]) + 12
            s[0] = str(k // 10)
            s[1] = str(k % 10)
        
    del s[-2:]
    s = ''.join(s)
    return s

x = timeConversion("07:05:45PM")
x

the code above output:

19:05:45

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM