在Python里,把字符串转换成列表的7种方法

方法一:使用list()方法

方法二:使用列表解析

方法三:使用字符串切片

方法四:使用enumerate方法

str = 'good'

after1 = list(str)
print('使用list()方法:', after1)

after2 = [i for i in str]
print('使用列表解析:', after2)

after3 = []
after3[:0] = str
print('使用字符串切片:', after3)

after4 = [i for a,i in enumerate(str)]
print('使用enumerate方法:', after4)

运行后输出:

​​​​​​​

方法五:使用split()方法

str2 = 'glad-to-see-you'
after5 = str2.split('-')
print('使用split()方法:', after5)

运行后输出:

方法六:使用JSON模块

方法七:使用ast.literal

import ast
import json

str3 = '["glad",1,"to",2,"see",3,"you"]'

after6 = json.loads(str3)
print('使用JSON模块:', after6)

after7 = ast.literal_eval(str3)
print('使用ast.literal:', after7)

运行后输出:

文章参考:Python | 将字符串转换为列表的7种方法_python字符串转换为列表-CSDN博客

版权声明:本文为博主作者:阿尔卑斯星208原创文章,版权归属原作者,如果侵权,请联系我们删除!

原文链接:https://blog.csdn.net/qq_29037259/article/details/134103679

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
心中带点小风骚的头像心中带点小风骚普通用户
上一篇 2024年1月6日
下一篇 2024年1月6日

相关推荐