你如何评估一个字符串并且你无法评估的单词保持不变?

how to you evaluate a string and the words that you can't evaluate keep the same?

string = input()
string = (''.join([str(eval(s)) if ('(' in s and ')' in s) else s for s in string.split(' ')]))
print(string)

此代码存在一些问题:

  1. 如果我写 5-(2-sp.sqrt(4)) 它会给我一个 EOF 错误,因为它会以 sp.sqrt( 4) 将是 sp.sqrt(4))。应该是 sp.sqrt(4)

  2. 如果我写“2-10”,它不会评估它,只会 return“2-10”;它应该 return '-8'。而如果我写“2-10*(2-5)”,它将 return 写入答案。

  3. 而不是不评估代码无法识别的部分,它会给我一个错误,指出未识别的部分未定义。 (例如 '2+x-10-(5*10)' ---- 名称 'x' 未定义。它应该 return: 'x-58'

问题 - 1:

it will give me an EOF error because it will split the words in a way that sp.sqrt(4) will be sp.sqrt(4))

  • 不,它不会那样拆分字符串,因为您使用 ' ' 拆分字符串,因此拆分函数的输出将为 ['5-(2-sp.sqrt(4))']
  • 它不会给出错误,除非并且直到您的输入具有有效的 python 表达式(在这种情况下,我怀疑问题出在 sp

问题 - 2:

if I write '2-10' it won't evaluate it and will just return '2-10' but when I write '2-10*(2-5)' it will return the write answer.

因为只有'('和')'都存在才调用了eval()函数

问题 - 3:

这是因为 eval() 只接受有效的 python 表达式(你不能将未声明的变量直接放在参数中)。在你的情况下 x 之前没有声明过。

解法:

有一个 sympy 函数 parse_expr 可能会做你想做的事:

In [20]: from sympy import parse_expr

In [21]: parse_expr('5-(2-sqrt(4))')
Out[21]: 5

In [22]: parse_expr('2-10')
Out[22]: -8

In [23]: parse_expr('2+x-10-(5*10)')
Out[23]: x - 58