Python无法将'list'对象转换为str错误。

10

我正在使用最新的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解释器一样困惑:你想要什么输出? - 5gon12eder
请查看https://dev59.com/YW035IYBdhLWcg3wHsKR。 - Denise
3个回答

16

目前情况下,您正在尝试在最后的打印语句中连接一个字符串和一个列表,这将引发 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

3
print("Here is the whole thing : " + str(letters))

你需要先将你的List对象转换为String

1
除了使用 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']

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


print(str(letters)[3:]) 这对你来说可以运行 - Arpit jain

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接