且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-09-06 19:50:52

可以使用 str.split 方法.

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

如果要将其转换为元组,只需

>>>打印元组(my_list)('A', 'B', 'C', 'D', 'E')

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

>>>my_list.append('F')>>>打印 my_list['A', 'B', 'C', 'D', 'E', 'F']

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']

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']