Answers:
您可以使用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']
"".split(",")
返回[""]
(一个包含一个元素的列表,该列表为空字符串)。
对于字符串中包含的整数,如果要避免将它们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]
>>> some_string='A,B,C,D,E'
>>> new_tuple= tuple(some_string.split(','))
>>> new_tuple
('A', 'B', 'C', 'D', 'E')
您可以使用此功能将以逗号分隔的单个字符串转换为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')