在Python里,把字符串转换成列表的7种方法 |
您所在的位置:网站首页 › 怎么把字符串切片打开 › 在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博客 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |