python - 在 Python 中将字符串转换为整数表达式
问题描述
假设我有一个这样的字符串:
"(((((908488990) - (255272197)) + ((-287634246) - (1144917742))) + (((1178779462) + (1410551276)) - ((-244815224) - (-722994984)))) + ((((-1134622847) - (-818189911)) + ((-479615696) + (-938948012))) + (((-1762293529) + (1281608170)) - ((1468184728) + (-895014314)))))"
如何在 Python 中将其转换为这样的表达式(不带引号):
(((((908488990) - (255272197)) + ((-287634246) - (1144917742))) + (((1178779462) + (1410551276)) - ((-244815224) - (-722994984)))) + ((((-1134622847) - (-818189911)) + ((-479615696) + (-938948012))) + (((-1762293529) + (1281608170)) - ((1468184728) + (-895014314)))))
这样我就可以得到该表达式的结果:
-1457036634
解决方案
如果您想处理@Hymns-For-Disco 提到的用户输入中的字符串,使用 eval 可能会很危险。
这是一个关于如何处理此类字符串的示例,它有点长,部分可以放在子函数中,但它给出了正确的输出(加上括号检查):
test_string = r"(((((908488990) - (255272197)) + ((-287634246) - (1144917742))) + (((1178779462) + (1410551276)) - ((-244815224) - (-722994984)))) + ((((-1134622847) - (-818189911)) + ((-479615696) + (-938948012))) + (((-1762293529) + (1281608170)) - ((1468184728) + (-895014314)))))"
import operator
operators = {'+' : operator.add, '-' : operator.sub} # you can add other operators here like operator.multiply
def compute(string):
operator = None
value_left = None
it = iter(string)
while True:
try:
character = next(it)
except StopIteration:
break
if character ==' ': continue
if character == '(':
count = 1 #count open parenthesis
sub_string = ''
while True:
try:
character = next(it)
except StopIteration:
raise(EOFError("Not matching parenthesis"))
if character == '(':
count+=1
if character == ')':
if count == 1:
break
else:
sub_string+= character
count-=1
else:
sub_string+= character
if operator is None:
print('call compute with{}'.format(sub_string))
value_left = compute(sub_string)
continue
else:
return operator(value_left,compute(sub_string))
if character.isdigit():
temp_num = character
while character.isdigit() or character=='.':
try:
character = next(it)
except StopIteration:
break
temp_num+= character
if operator is None:
value_left = float(temp_num)
else:
return operator(value_left, float(temp_num))
if character in operators.keys():
operator = operators[character]
#test for unary '-' operator:
if character == '-' and value_left is None:
value_left = 0.0
return value_left
print(compute(test_string)) #returns -1457036634.0
test_string =r'(3+4'
print(compute(test_string)) # raises EOFError: Not matching parenthesis
希望对你有帮助
推荐阅读
- angular - 如何在 Angular 中分配 formControlName?
- hadoop - 在 Cloudera Manager 中没有“启动”服务的情况下,Hadoop 服务仍在运行
- java - 生成 shim `.so` 以重命名现有 `.so` 的符号
- angular - 订阅基类中的行为主题时,Rxjs 订阅不起作用
- c - Update cell in struct list and return the list
- oracle - Double Pivot across columns is failing
- python - 根据 if 语句更改 Tkinter 标签文本?
- php - 使用 ajax 发送自定义电子邮件 - woocommerce / wordpress 用户注册
- spring-boot - 在 Spring MVC 集成测试中处理我的自定义异常
- webrtc - 使用 SSL(本地)的 Freeswitch 与 webRTC