(1) str->list
s = '12345'
l = list(s)
结果:['1', '2', '3', '4', '5']
(2) list->str
l = ['1','2','3']
s = ''.join(l)
结果:'123'
如果list里的元素是int型而非str型则比较麻烦,还这样写会报错,而在刷题时经常碰到需要将int型的list输出为str的情况,于是补充以下两种情况:
(3) str->list(元素是int型)
s = '12345'
list(map(int, '12345'))
结果:[1, 2, 3, 4, 5]
(4) list(元素是int型)->str
l = [1,2,3]
s = ''.join(l)
按照(2)这样写会报错:TypeError: sequence item 0: expected str instance, int found,因为join函数的对象应该是str而不能是int,需要借助map()函数将list内每个元素转为str型,再join().
s = ''.join(map(str,l))
结果:'123'