Python eval(string == string)

问题描述 投票:-1回答:2

我正在尝试使用eval函数来读取字符串并评估字符串中的内容。

a = 'red'
b = '=='
c = 'red'
print(eval(a+b+c))

它给我一个错误

NameError: name 'red' is not defined

注意:我知道它评估为红色==红色并将其作为变量而不是字符串读取但不知道如何在评估过程中使其成为字符串,即'red'=='red'

比我尝试过ast

import ast
ast.literal_eval(a+b+c)

但是给出了一个错误:

ValueError: malformed node or string: <_ast.Compare object at 0x035706F0>

比我尝试ast.parse,但我不想写基于运算符的单独的函数/方法,如果它可以用eval只做功能/方法

任何建议或有用资源的链接将不胜感激。

python string python-3.x eval
2个回答
1
投票
a = "'red'"
c = "'red'"

更常见的方法是使用repr

repr('red') # -> "'red'"
repr('"blue"') # -> '\'"blue"\'' (this does actually evaluate to '"blue"')

2
投票

虽然你正在做的是一个糟糕的想法,并且可以通过其他方式完成,但你需要在字符串中添加引号:

a = '\'red\''
b = ' == '
c = '\'red\''

要么

a = '"red"'
b = ' == '
c = '"red"'

要么

a = "'red'"
b = ' == '
c = "'red'"

其中任何一个都应该有效。根据您想要的报价类型和您愿意做的逃避金额,您可以选择。

另外,您不需要为特定示例使用eval

a == c

将给出eval的结果。如果您担心不知道运算符,请使用dictoperator模块:

import operator

ops = {
    '==': operator.eq,
    '<': operator.lt,
    '<=': operator.le,
    ...
}
ops[b](a, c)
© www.soinside.com 2019 - 2024. All rights reserved.