python - Python literal_eval 无效语法
问题描述
当我试图这样做时:
literal_eval('[Alices Adventures in Wonderland, and, Through the Looking-Glass, by, Lewis Carroll]')
我收到此错误:
File "<unknown>", line 1
[Alices Adventures in Wonderland, and, Through the Looking-Glass, by, Lewis Carroll]
^
SyntaxError: invalid syntax
我希望得到一个这样的列表对象:
[Alices Adventures in Wonderland, and, Through the Looking-Glass, by, Lewis Carroll]
编辑:
好的,所以我试图得到的是一个列表,里面会有字符串元素。这不起作用,因为literal_eval
列表中的对象不是字符串之后。
所以,最后为了找到我的解决方案,我这样做了:
'[Alices Adventures in Wonderland, and, Through the Looking-Glass, by, Lewis Carroll]'.strip("[]").split(",")
这给出了输出:
['Alices Adventures in Wonderland', ' and', ' Through the Looking-Glass', ' by', ' Lewis Carroll']
解决方案
在列表中,字符串项用引号括起来:
literal_eval('["Alices Adventures in Wonderland", "and", "Through the Looking-Glass", "by", "Lewis Carroll"]')
推荐阅读
- c# - Spire Xls 设置单元格范围十六进制格式
- unity3d - 如何修复 Unity 教程“识别本地播放器”OnStartLocalPlayer() 中的错误?
- c# - 在自定义按钮中模仿 TextImageRelation 的行为
- angular - Angular 6 - 隐藏或显示从服务触发的组件中的 Div
- single-sign-on - Alfresco 无法使用 CAS SSO 连接到存储库
- sql - 正则表达式过滤带点和不带点的数字
- python - Flask-SQLAlchemy ORM/GeoAlchemy2 结果到字典,最终是 JSON
- css - ReactJs - 对齐导航栏项目
- javascript - 如何显示 href 的 react-intl 翻译结果?
- javascript - 在 JavaScript 中对数组进行排序