【问题标题】:Python cant convert 'list' object to str error [closed]Python无法将“列表”对象转换为str错误[关闭]
【发布时间】:2014-11-08 03:12:34
【问题描述】:

我正在使用最新的 Python 3

letters = ['a', 'b', 'c', 'd', 'e']
letters[:3]
print((letters)[:3])
letters[3:]
print((letters)[3:])
print("Here is the whole thing :" + letters)

错误:

Traceback (most recent call last):
  File "C:/Users/Computer/Desktop/Testing.py", line 6, in <module>
    print("Here is the whole thing :" + letters)
TypeError: Can't convert 'list' object to str implicitly

修复时,请解释它是如何工作的 :) 我不想只是复制固定的行

【问题讨论】:

标签: python string python-3.x list typeerror


【解决方案1】:

就目前而言,您正试图在最终的打印语句中将一个字符串与一个列表连接起来,这将抛出TypeError

相反,将您最后的打印语句更改为以下之一:

print("Here is the whole thing :" + ' '.join(letters)) #create a string from elements
print("Here is the whole thing :" + str(letters)) #cast list to string

【讨论】:

    【解决方案2】:
    print("Here is the whole thing : " + str(letters))
    

    您必须首先将您的 List-object 转换为 String

    【讨论】:

      【解决方案3】:

      除了str(letters) 方法之外,您还可以将列表作为独立参数传递给print()。来自doc 字符串:

      >>> print(print.__doc__)
      print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
      
      Prints the values to a stream, or to sys.stdout by default.
      

      因此可以将多个值传递给print(),它将按顺序打印它们,以sep的值分隔(默认为' '):

      >>> print("Here is the whole thing :", letters)
      Here is the whole thing : ['a', 'b', 'c', 'd', 'e']
      >>> print("Here is the whole thing :", letters, sep='')   # strictly your output without spaces
      Here is the whole thing :['a', 'b', 'c', 'd', 'e']
      

      或者你可以使用字符串格式:

      >>> letters = ['a', 'b', 'c', 'd', 'e']
      >>> print("Here is the whole thing : {}".format(letters))
      Here is the whole thing : ['a', 'b', 'c', 'd', 'e']
      

      或字符串插值:

      >>> print("Here is the whole thing : %s" % letters)
      Here is the whole thing : ['a', 'b', 'c', 'd', 'e']
      

      这些方法通常优于使用 + 运算符的字符串连接,尽管这主要是个人喜好问题。

      【讨论】:

        猜你喜欢
        • 2017-12-21
        • 2020-02-24
        • 1970-01-01
        • 2013-09-27
        • 2019-04-11
        • 2018-12-26
        • 1970-01-01
        • 1970-01-01
        • 2017-03-27
        相关资源
        最近更新 更多