【发布时间】:2019-04-11 12:13:51
【问题描述】:
我正在尝试将字符串转换为列表。
stringvalue = '[54.0, country, state]'
我遇到了很多答案,但所有的字符串都会有这样的引号
[54.0, 'country', 'state']
所以我的想法是我想要一个这样的列表
[54.0, country, state]
基本上,国家和州是变量,将在程序中得到解决。
环顾四周后,我遇到了一个答案,它使用 this 删除了字符串周围的引号(')
class MyStr(str):
""" Special string subclass to override the default representation method
which puts single quotes around the result.
"""
def __repr__(self):
return super(MyStr, self).__repr__().strip("'")
MyStr(stringvalue)
这导致输出看起来像列表(不带引号)
[54.0, country, state]
但是类型是__main__.MyStr.- 没有列出我在看什么
关于如何解决这个问题的任何想法?
【问题讨论】:
-
你知道国家和州变量的值吗?
-
eval(stringvalue)将在country和state已定义或eval(stringvalue, locals=dict(country='US', state='GA'))已定义的情况下工作 -
所以
country和state是 placeholders‽ 然后你想要一个简单的子字符串替换,或者你想要为你的迷你表达式语言编写一个迷你解析器,它可以计算像这样的自定义关键字。 -
@deceze 是的,国家和州就像占位符。
-
@martineau 抱歉,您说的完全正确。我应该说:
eval(stringvalue, {}, dict(country='US', state='GA'))。见eval。我一直不明白为什么有些函数显然应该没有关键字参数。
标签: python string list replace