首页 > 解决方案 > 这些代码有什么区别?为什么它们有不同的输出?

问题描述

list = ['first', 'second', 'third', 'fourth']
s = '/'
newList = s.join(list)
print(newList)

此代码输出

"first/second/third/fourth"

list = ['first', 'second', 'third', 'fourth']
s = '/'
newList = s.join(str(list))
print(newList)

此代码输出

 "[/'/f/i/r/s/t/'/,/ /'/s/e/c/o/n/d/'/,/ /'/t/h/i/r/d/'/,/ /'/f/o/u/r/t/h/'/]"

这里做了什么str()导致列表按每个字母分开?

标签: pythonpython-3.x

解决方案


str()创建一个字符串,如"['first', 'second', 'third', 'fourth']".

并将s.join()字符串视为 char 数组。然后它放在'/'数组中的每个元素之间。


推荐阅读