将字符串转换为列表.Python [string.split() 表现得很奇怪] [英] Convert string to list. Python [string.split() acting weird]

查看:24
本文介绍了将字符串转换为列表.Python [string.split() 表现得很奇怪]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

temp = "['a','b','c']"打印类型(温度)#细绳输出 = ['a','b','c']打印类型(输出)#列表

所以我有这个临时字符串,它基本上是一个字符串格式的列表...我正试图把它变成一个列表,但我不确定一个简单的方法来做到这一点.我知道一种方法,但我宁愿不使用正则表达式

如果我使用 temp.split() 我得到

temp_2 = ["['a','b','c']"]

解决方案

使用 ast.literal_eval():

<块引用>

安全地评估一个表达式节点或一个 Unicode 或 Latin-1 编码的包含 Python 表达式的字符串.提供的字符串或节点可能仅包含以下 Python 文字结构:字符串、数字、元组、列表、字典、布尔值和无.

<预><代码>>>>从 ast 导入literal_eval>>>temp = "['a','b','c']">>>l =literal_eval(temp)>>>升['a', 'b', 'c']>>>类型(l)<输入列表">

temp = "['a','b','c']"
print type(temp)
#string

output = ['a','b','c']
print type(output)
#list

so i have this temporary string which is basically a list in string format . . . i'm trying to turn it back into a list but i'm not sure a simple way to do it . i know one way but i'd rather not use regex

if i use temp.split() I get

temp_2 = ["['a','b','c']"]

解决方案

Use ast.literal_eval():

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

>>> from ast import literal_eval
>>> temp = "['a','b','c']"
>>> l = literal_eval(temp)
>>> l
['a', 'b', 'c']
>>> type(l)
<type 'list'>

这篇关于将字符串转换为列表.Python [string.split() 表现得很奇怪]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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