【问题标题】:How to fix TypeError: can only concatenate str (not "list") to str如何修复 TypeError:只能将 str(不是“list”)连接到 str
【发布时间】:2019-05-26 11:42:59
【问题描述】:

我正在尝试从 python 速成课程中学习 python,但是这一项任务让我很难过,我在任何地方都找不到答案

任务是 想一想您最喜欢的交通方式,并列出一个包含几个示例的列表 使用您的列表打印有关这些项目的一系列陈述

cars = ['rav4'], ['td5'], ['yaris'], ['land rover tdi'] 

print("I like the "+cars[0]+" ...")

我假设这是因为我将字母和数字放在一起,但我不知道如何生成没有错误的结果,我们将不胜感激地获得帮助 我得到的错误是

TypeError: 只能将 str(不是“list”)连接到 str**

【问题讨论】:

  • 试试这个:cars = ['rav4', 'td5', 'yaris', 'land rover tdi']
  • 太好了,谢谢,我知道这是一个菜鸟问题,但它真的难倒我,我非常感激谢谢

标签: python typeerror


【解决方案1】:
new_dinner = ['ali','zeshan','raza']
print ('this is old friend', new_dinner)

使用逗号, 而不是加号+

如果你在print ('this is old friend' + new_dinner) 语句中使用加号+ 会出错。

【讨论】:

    【解决方案2】:

    您的第一行实际上生成了一个列表元组,因此 cars[0] 是一个列表。

    如果你打印cars,你会看到它看起来像这样:

    (['rav4'], ['td5'], ['yaris'], ['land rover tdi'])
    

    去掉中间的所有方括号,你会得到一个可以索引的列表。

    【讨论】:

      【解决方案3】:

      这是您可以用来获得所需结果的可能性之一。 它学习导入、使用格式化方法和将数据类型存储在变量中,以及如何将不同的数据类型转换为字符串数据类型! 但是您要做的主要事情是将列表或您希望的索引转换为字符串。通过使用str(----) 函数。但问题是你已经创建了 4 个列表,你应该只有一个!

      from pprint import pprint
      cars = ['rav4'], ['td5'], ['yaris'], ['land rover tdi']
      Word = str(cars[0])
      pprint("I like the {0} ...".format(Word))
      

      【讨论】:

      • pprint 是不必要的,这看起来不像OP希望的那样以所需的格式输出。例如:这输出“我喜欢 ['rav4'] ...”,其中 OP 想要“我喜欢 rav4 ...”。
      【解决方案4】:

      首先,创建一个字符串列表(不是列表元组),然后您可以访问列表的第一个元素(字符串)。

      cars = ['rav4', 'td5', 'yaris', 'land rover tdi']
      print("I like the "+cars[0]+" ...")
      

      以上代码输出:I like the rav4 ...

      【讨论】:

        【解决方案5】:

        你可以这样做

        new_dinner = ['ali','zeshan','raza']
        print ('this is old friend', *new_dinner)
        

        【讨论】:

          【解决方案6】:

          给你答案:

          cars = (['rav4'], ['td5'], ['yaris'], ['land rover tdi']) 
          
          print("I like the "+cars[0][0]+" ...")
          

          我们在这里所做的是先调用列表,然后调用列表中的第一项。 由于您将数据存储在元组中,因此这是您的解决方案。

          【讨论】:

            【解决方案7】:
                new_dinner = ['ali','zeshan','raza']
                print ('this is old friend', str(new_dinner))
            
                #Try turning the list into a strang only
            

            【讨论】:

            • 字符串*********\
            • 我认为'strang'只是一个评论。不应导致错误。
            • 我知道这一点,但我在评论中纠正了这个错误,我知道这并不重要,但这是一个拼写错误
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-02-06
            • 2020-10-20
            • 1970-01-01
            • 2020-09-18
            • 2020-08-19
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多