Python | 您所在的位置:网站首页 › python中的长度转换 › Python |
在本文中,我们将尝试将给定的字符串转换为列表,其中根据用户的选择,遇到空格或任何其他特殊字符。为此,我们在string中使用split()方法。 例如: 输入: “Geeks for Geeks” 输出: [‘Geeks’, ‘for’, ‘Geeks’] 1. 使用list()方法列表是Python中内置的数据类型。它通常用于存储项目或项目集合,我们可以用它将字符串转换为列表。 s = "abcd" x = list(s) print(x)输出 ['a', 'b', 'c', 'd'] 2. 使用列表解析 s="abcd" x=[i for i in s] print(x)输出 ['a', 'b', 'c', 'd'] 3. 使用split()方法split方法用于拆分字符串并将其存储在列表中。内置方法返回字符串中的单词列表,使用“分隔符”作为分隔符字符串。如果未指定分隔符或分隔符为None,则应用不同的拆分算法:连续空格的运行被视为单个分隔符,并且如果字符串具有前导或尾随空格,则结果在开始或结束处将不包含空字符串。 def Convert(string): li = list(string.split(" ")) return li # Driver code str1 = "Geeks for Geeks" print(Convert(str1))输出 ['Geeks', 'for', 'Geeks'] def Convert(string): li = list(string.split("-")) return li # Driver code str1 = "Geeks-for-Geeks" print(Convert(str1))输出 ['Geeks', 'for', 'Geeks'] 4. 使用字符串切片 def Convert(string): list1 = [] list1[:0] = string return list1 # Driver code str1 = "ABCD" print(Convert(str1))输出 ['A', 'B', 'C', 'D'] 5. 使用enumerate方法 s="abcd" x=[i for a,i in enumerate(s) ] print(x)输出 ['a', 'b', 'c', 'd'] 6. 使用JSON模块 import json stringA = '["geeks", 2,"for", 4, "geeks",3]' # Type check res = json.loads(stringA) # Result print("The converted list : \n",res)输出 The converted list : ['geeks', 2, 'for', 4, 'geeks', 3] 7. 使用ast.literal在Python中,有个ast模块,它有一个litera_eval方法,我们也可以通过它来进行转换。 import ast # initializing string representation of a list ini_list = '["geeks", 2,"for", 4, "geeks",3]' # Converting string to list res = ast.literal_eval(ini_list) # printing final result and its type print(res) print(type(res))输出 ['geeks', 2, 'for', 4, 'geeks', 3] |
CopyRight 2018-2019 实验室设备网 版权所有 |