python 字符串(str)和列表(list)互相转换


字符串转列表

第一种情况:

#字符串 
a = '1,2,3'

a_lst = a.split(',')
#结果:['1', '2', '3']

第二种情况:

#字符串
a = 'abcdef'
a_lst = list(a) print(a_lst) #结果['a', 'b', 'c', 'd', 'e', 'f']

列表转字符串

第一种情况:

#列表
lst = [1, 2, 3]   #如果列表中的元素有int型,必须先把int转成str,然后在做字符串拼接
new_lst = []  
for i in lst:
  i
= str(i)
  new_lst.append(i)

str
= ''.join(new_lst)
print(str)
#结果: 123

第二种情况:

#列表
lst = ['a', 'b', 'c', 'd', 'e', 'f','123']   #列表中的所有元素都是字符串

str = ''.join(lst)
print(str)
#结果:abcdef123

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM