基本上在这个任务中,我们必须根据ran(小时,分钟)的值创建一个时间:下面我将发布我的代码,然后发送我收到的错误消息。我的代码真的很糟糕还是我错过了什么?它是什么意思"无法转换' int'隐含地反对str。
def show_time(hour,min):
if(hour > 12):
hour = hour -12
if(min < 10):
min = "0"+min
print("{hour}:{min}".format(show_time()))
Traceback (most recent call last):
File "zyLabsUnitTestRunner.py", line 10, in <module>
passed = test_passed(test_passed_output_file)
File "/home/runner/local/unit_test_student_code/zyLabsUnitTest.py", line 33, in test_passed
ans = show_time(hour,min)
File "/home/runner/local/unit_test_student_code/main.py", line 15, in show_time
min = "0"+min
TypeError: Can't convert 'int' object to str implicitly
答案 0 :(得分:0)
在以下行中:
if(min<10):
min = "0"+min
你试图连接一个字符串和一个整数,python不能这样做。要将字符串转换为int,请使用int(str),并将int转换为字符串,请使用str(int)
答案 1 :(得分:0)
您收到此错误的原因是因为您将"0"
(一个字符串)与min
连接起来,这是一个整数。
>>> '0' + 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
您可以通过将min
转换为字符串来避免这种情况:
>>> '0' + str(3)
'03'
但最好的解决方案是保存这种格式 - 您猜对了! - str.format()
。它有http://www.videomap.it/forum/viewtopic.php?t=1604,允许您将这些转换保留在它们所属的位置。这是一个例子:
>>> '{:02d}'.format(3)
'03'
目前,您的代码有几个问题:
>>> '{a}:{b}'.format(**{'a':1, 'b':2}) '1:2'
min
是变量的错误名称,因为它是内置函数。这是在一个区块内完成所有事情的更简单方法:
print("{}:{:02d}".format(hour % 12, minute))
答案 2 :(得分:0)
我认为你使用的格式不正确,你不能连接'str'和'int'对象(min =“0”+ min)。我认为这有效:
def show_time(hour,min):
if(hour > 12):
hour = hour -12
if(min < 10):
min = "0" + str(min)
print "{}:{}".format(hour, min)