[英]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.我试图创建一个 function timeConversion 以 12 小时时间格式作为输入并返回 24 小时时间格式。 The input is a string containing time in 12-hour format ie
hh:mm:ssAM
, hh:mm:ssPM
.输入是一个包含 12 小时格式时间的字符串,即
hh:mm:ssAM
、 hh:mm:ssPM
。 The hh
, mm
, ss
represent hour, minute, and second respectively. hh
、 mm
、 ss
分别代表小时、分钟和秒。
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在第 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'
类型错误:+ 的不支持的操作数类型:“int”和“str”
I tried using我尝试使用
type(int(s[0]+s[1]))
and it return int type, so what did I miss?它返回 int 类型,那么我错过了什么?
In the line在行
s[1] = (int(s[0]+s[1]) + 12) % 10 s[1] = (int(s[0]+s[1]) + 12) % 10
You converted int(s[0]+s[1]).您转换了 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[0] = '1' 和 s[1] = '2',那么它会给出 12。但你需要 3。所以用下面的行替换第 10 行..
s[1] = (int(s[0])+int(s[1]) + 12) % 10
Maybe your list s
contains strings, therefore也许您的 list
s
包含字符串,因此
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.结果是导致问题的
int
。
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: output上面的代码:
19:05:45
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.