如何在Python中将逗号分隔的字符串转换为列表?
给定一个由逗号分隔的多个值组成的序列:
mStr = 'A,B,C,D,E'
如何将字符串转换为列表?
mList = ['A', 'B', 'C', 'D', 'E']
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']
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以使用 str.split 方法。
如果您想将其转换为元组,
如果您想附加到列表,请尝试以下操作:
You can use the str.split method.
If you want to convert it to a tuple, just
If you are looking to append to a list, try this:
对于字符串中包含整数的情况,如果您想避免将它们单独转换为
int
,您可以这样做:它称为列表理解,它基于关于集合构建器符号。
前任:
In the case of integers that are included at the string, if you want to avoid casting them to
int
individually you can do:It is called list comprehension, and it is based on set builder notation.
ex:
为了处理空字符串的情况,请考虑以下事项:
Consider the following in order to handle the case of an empty string:
您可以将该字符串拆分为
,
并直接获取列表:输出:
您还可以将其转换为 n 元组:
输出:
You can split that string on
,
and directly get a list:Output:
You can also convert it to an n-tuple:
Output:
您可以使用此函数将逗号分隔的单个字符串转换为列表 -
You can use this function to convert comma-delimited single character strings to list-