如何将逗号分隔的字符串转换为Python中的列表? [英] How to convert comma-delimited string to list in Python?
本文介绍了如何将逗号分隔的字符串转换为Python中的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出一个字符串,该字符串是由逗号分隔的多个值的序列:
Given a string that is a sequence of several values separated by a commma:
mStr = 'A,B,C,D,E'
如何将字符串转换为列表?
How do I convert the string to a list?
mList = ['A', 'B', 'C', 'D', 'E']
推荐答案
您可以使用str.split方法.
You can use the str.split method.
>>> my_string = 'A,B,C,D,E'
>>> my_list = my_string.split(",")
>>> print my_list
['A', 'B', 'C', 'D', 'E']
如果要将其转换为元组,只需
If you want to convert it to a tuple, just
>>> print tuple(my_list)
('A', 'B', 'C', 'D', 'E')
如果您希望添加到列表中,请尝试以下操作:
If you are looking to append to a list, try this:
>>> my_list.append('F')
>>> print my_list
['A', 'B', 'C', 'D', 'E', 'F']
这篇关于如何将逗号分隔的字符串转换为Python中的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文