Python 无法将“列表”对象转换为 str 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/25833715/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python cant convert 'list' object to str error
提问by Excetera
I am using the latest Python 3
我正在使用最新的 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)
Error:
错误:
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
When fixing, please explain how it works :) i dont want to just copy a fixed line
修复时,请解释它是如何工作的 :) 我不想只复制固定行
采纳答案by u1860929
As it currently stands, you are trying to concatenate a string with a list in your final print statement, which will throw TypeError.
按照目前的情况,您正试图在最终的打印语句中将字符串与列表连接起来,这将抛出TypeError.
Instead, alter your last print statement to one of the following:
相反,将您的最后一个打印语句更改为以下内容之一:
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
回答by Leistungsabfall
print("Here is the whole thing : " + str(letters))
You have to cast your List-object to Stringfirst.
您必须首先将您的List-object 转换为String。
回答by mhawke
In addition to the str(letters)method, you can just pass the list as an independent parameter to print(). From the docstring:
除了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.
So multiple values can be passed to print()which will print them in sequence, separated by the value of sep(' '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']
Or you can use string formatting:
或者您可以使用字符串格式:
>>> letters = ['a', 'b', 'c', 'd', 'e']
>>> print("Here is the whole thing : {}".format(letters))
Here is the whole thing : ['a', 'b', 'c', 'd', 'e']
Or string interpolation:
或字符串插值:
>>> print("Here is the whole thing : %s" % letters)
Here is the whole thing : ['a', 'b', 'c', 'd', 'e']
These methods are generally preferred over string concatenation with the +operator, although it's mostly a matter of personal taste.
这些方法通常比使用+运算符的字符串连接更受欢迎,尽管这主要是个人喜好的问题。

