Python无法转换';列表';对象到str错误

Python无法转换';列表';对象到str错误,python,string,python-3.x,list,typeerror,Python,String,Python 3.x,List,Typeerror,我正在使用最新的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",

我正在使用最新的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
回溯(最近一次呼叫最后一次):
文件“C:/Users/Computer/Desktop/Testing.py”,第6行,在
打印(“全部内容如下:+字母)
TypeError:无法将“list”对象隐式转换为str

当修复时,请解释它是如何工作的:)我不想只复制一个固定行,因为它当前的状态,您正在尝试在最终打印语句中将字符串与列表连接起来,这将抛出
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

您必须首先将
列表
-对象强制转换为
字符串

除了
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
的值分隔(默认情况下,
'
):

也可以使用字符串格式:

>>> 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']

这些方法通常比使用
+
运算符进行字符串连接更受欢迎,尽管这主要是个人喜好的问题。

我和您的Python解释器一样困惑:您想要什么输出?请查看。
>>> 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']