Python实现拼接列表中的元素

记录日常学习遇到的问题

1.列表中的元素为字符串时

l1=['a','p','p','l','e']
l2=''.join(l1)
print(l2)

[outs]:
apple

2.列表中的元素为数字时,不能用join直接拼接列表中的元素

l1=[2,0,2,1]
l2=''.join(l1)
print(l2)

[outs]:
TypeError: sequence item 0: expected str instance, int found

正确的方式为将列表中的数字遍历后转化为str类型再拼接,具体操作如下

l1=[2,0,2,1]
l2=''.join(str(num) for num in l1)
print(l2)

[outs]:
2021

猜你喜欢

转载自blog.csdn.net/qq_42548340/article/details/121828161
今日推荐