【Python 实战】 列表与字符串的转换
列表转换为字符串
‘’.join()函数
- 需要新的变量接收返回的字符串
只能处理值全部为字符串类型的列表
newstr='列表值之间添加的内容'.join(someList)
列表单词连句子:1
2
3someList=['this','is','an','example']
newStr=' '.join(someList) # 在每个值之间添加一个' '组成新的字符串
print(newStr)
This is an example
列表数值无缝连接:1
2
3someList=['0','-','6','7','0','-','8','2','1','6','2','-','4']
newStr=''.join(someList) #在每个值之间添加''无缝连接
print(newStr)
0-670-82162-4
只能处理值全部为字符串类型的列表:1
2
3someList=['0','-','6','7','0','-','8','2','1','6','2','-',4]
newStr=''.join(someList)
print(newStr)
**报错** (因为列表中存在int整型值)
字符串转换为列表
list()函数
会将字符串中的每个字符(包括空格)全部打散成值
1
2
3spam='This is an example'
newList=list(spam)
print(newList)['T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', 'n', ' ', 'e', 'x', 'a', 'm', 'p', 'l', 'e']
split()函数
- 会根据传入的参数打散字符串,默认参数是’\n’(换行符)
需要新的列表来接收
newList=字符串.split()
句子打散成单词:传入’ ‘打散句子1
2
3spam='This is an example'
newList=spam.split(' ')
print(newList)
['This', 'is', 'an', 'example']
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 SYolin's Blog!
评论