我正在使用最新的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
修复时,请解释它是如何工作的:)我不想复制固定的行
答案 0 :(得分:16)
目前的情况是,您正在尝试将字符串与最终print语句中的列表连接起来,该列表将抛出TypeError
。
相反,将您的上一个print语句更改为以下之一:
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
答案 1 :(得分:3)
print("Here is the whole thing : " + str(letters))
您必须先将List
- 对象转换为String
。
答案 2 :(得分: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']
这些方法通常比使用+
运算符的字符串连接更受欢迎,尽管这主要取决于个人品味。