如何在Python中将带有逗号分隔的项目的字符串转换为列表? [英] How to convert a string with comma-delimited items to a list in Python?

查看:537
本文介绍了如何在Python中将带有逗号分隔的项目的字符串转换为列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do you convert a string into a list?

说字符串类似于text = "a,b,c".转换后,text == ['a', 'b', 'c']并希望text[0] == 'a'text[1] == 'b'?

Say the string is like text = "a,b,c". After the conversion, text == ['a', 'b', 'c'] and hopefully text[0] == 'a', text[1] == 'b'?

推荐答案

像这样:

>>> text = 'a,b,c'
>>> text = text.split(',')
>>> text
[ 'a', 'b', 'c' ]

或者,如果您相信字符串是安全的,则可以使用eval():

Alternatively, you can use eval() if you trust the string to be safe:

>>> text = 'a,b,c'
>>> text = eval('[' + text + ']')

这篇关于如何在Python中将带有逗号分隔的项目的字符串转换为列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆