如何转换逗号分隔的字符串列表在Python?

给定一个字符串,它是由逗号分隔的几个值的序列:

mStr = 'A,B,C,D,E'

如何将字符串转换为列表?

mList = ['A', 'B', 'C', 'D', 'E']
427681 次浏览

你可以使用str.split方法。

>>> my_string = 'A,B,C,D,E'
>>> my_list = my_string.split(",")
>>> print my_list
['A', 'B', 'C', 'D', 'E']

如果你想把它转换成元组,只要

>>> print tuple(my_list)
('A', 'B', 'C', 'D', 'E')

如果你想追加到一个列表,试试这个:

>>> my_list.append('F')
>>> print my_list
['A', 'B', 'C', 'D', 'E', 'F']
>>> some_string='A,B,C,D,E'
>>> new_tuple= tuple(some_string.split(','))
>>> new_tuple
('A', 'B', 'C', 'D', 'E')

对于字符串中包含的整数,如果你想避免将它们单独转换为int,你可以这样做:

mList = [int(e) if e.isdigit() else e for e in mStr.split(',')]

它被称为列表理解,它基于集合构建器符号。

例:

>>> mStr = "1,A,B,3,4"
>>> mList = [int(e) if e.isdigit() else e for e in mStr.split(',')]
>>> mList
>>> [1,'A','B',3,4]

您可以使用此函数将逗号分隔的单个字符串转换为list-

def stringtolist(x):
mylist=[]
for i in range(0,len(x),2):
mylist.append(x[i])
return mylist
#splits string according to delimeters
'''
Let's make a function that can split a string
into list according the given delimeters.
example data: cat;dog:greff,snake/
example delimeters: ,;- /|:
'''
def string_to_splitted_array(data,delimeters):
#result list
res = []
# we will add chars into sub_str until
# reach a delimeter
sub_str = ''
for c in data: #iterate over data char by char
# if we reached a delimeter, we store the result
if c in delimeters:
# avoid empty strings
if len(sub_str)>0:
# looks like a valid string.
res.append(sub_str)
# reset sub_str to start over
sub_str = ''
else:
# c is not a deilmeter. then it is
# part of the string.
sub_str += c
# there may not be delimeter at end of data.
# if sub_str is not empty, we should att it to list.
if len(sub_str)>0:
res.append(sub_str)
# result is in res
return res


# test the function.
delimeters = ',;- /|:'
# read the csv data from console.
csv_string = input('csv string:')
#lets check if working.
splitted_array = string_to_splitted_array(csv_string,delimeters)
print(splitted_array)

为了处理空字符串的情况,考虑以下问题:

>>> my_string = 'A,B,C,D,E'
>>> my_string.split(",") if my_string else []
['A', 'B', 'C', 'D', 'E']
>>> my_string = ""
>>> my_string.split(",") if my_string else []
[]

你可以在,上拆分该字符串,并直接获得一个列表:

mStr = 'A,B,C,D,E'
list1 = mStr.split(',')
print(list1)

输出:

['A', 'B', 'C', 'D', 'E']

你也可以把它转换成n元组:

print(tuple(list1))

输出:

('A', 'B', 'C', 'D', 'E')