使用.format()

时间:2016-10-10 20:51:42

标签: python

基本上在这个任务中,我们必须根据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

3 个答案:

答案 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'

目前,您的代码有几个问题:

  1. 您在代码段中没有参数地调用它。
  2. 您正在使用格式函数中的变量 而不是其参数:您似乎混淆了传递关键字参数,如下所示:
  3. >>> '{a}:{b}'.format(**{'a':1, 'b':2})
    '1:2'
    
    1. 您没有使用该功能返回任何内容。
    2. min是变量的错误名称,因为它是内置函数。
    3. 这是在一个区块内完成所有事情的更简单方法:

      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)