我已经编写了一个代码,可以从字符串中提取int并在python中执行计算。
user_input = input('')
     if user_input[0:3] in ['add']:                                                                            
          print(int(user_input[4]) + int(user_input[10])) 代码只能添加一个数字,但我想要添加两个'n‘位数字
发布于 2017-03-27 11:49:40
您可以使用split()将输入字符串分解为操作和参数组件,然后执行算术操作。我假设您的输入具有以下格式:
<op> <arg1> <arg2>例如,
add 1 2如果用户输入add 100 24,那么当您拆分它时,您将得到以下内容:
>>> user_input = input()
add 100 24
>>> user_input.split()
['add', '100', '24']可以将split()返回的列表项绑定到如下所示的变量:
>>> op, arg1, arg2 = user_input.split()
>>> op
add
>>> arg1
100
>>> arg2
24为了执行操作,我们需要将参数作为数值(我假设可以输入浮点数):
>>> arg1 = float(arg1)
>>> arg2 = float(arg2)现在arg1和arg2分别是100.0和24.0。下一步是执行操作。可以使用字典将字符串映射到函数:
import operator
operations = {'add': operator.add,
              'sub': operator.sub,
              'mul': operator.mul,
              'div': operator.truediv}然后执行如下操作:
if op in operations:
    result = operations[op](arg1, arg2)
else:
    print('Invalid operation: {}'.format(op))现在您可以执行上述任何操作,例如div 100 20、sub 10 100等。
这可以通过使用op作为键在字典中查找操作,然后使用相应的值作为函数调用,将参数传递给该函数。
发布于 2017-03-27 11:26:53
如果您想要做的只是添加一些内容,您可以简单地按照单词add拆分您的字符串
test1 = "17 add 4"
summands = test1.split("add")
result = sum(int(s) for s in summands)
print(result)如果您想要做更高级的事情,您必须更加小心地拆分您的字符串。在这种情况下,正则表达式可以派上用场:
import re
test2 = "17 add 4 divide 3"
parts = re.split(r"(add|divide)", test2)
print(parts)这将给出数字、文字和运算符的列表。然后由您来将这个列表转换为一个计算。
当然,你也可以欺骗:
test3 = "(17 add 4) divide 3"
print(int(eval(test3.replace("add", "+").replace("divide", "/"))))如果无法控制输入(在本例中,攻击者可能使用eval执行任意代码),这是不安全的。
编辑添加:
由于我在拖延,我继续写了一个更完整的例子:
# Testcase
test4 = "((17 ADD 4) DIVIDE 3) MINUS 4"
# Define stuff that can appear inside an expression:
operators = ["add", "subtract", "minus", "multiply", "times", "divide"]
parens = [r"\(", r"\)"]
replacements = {
    "add": "+", "subtract": "-", "minus": "-", "multiply": "*",
    "times": "*", "divide": "/",
}    
tokens = operators + parens
baretokens = [t.replace("\\", "") for t in tokens]
delims = "({0})".format("|".join(tokens))
# Split the testcase in its parts
parts = re.split(delims, test4.lower())
print(parts)
# Replace operators with their Python counterparts:
result = ""
for p in parts:
    if p.strip().isdigit():
        result += p
    elif p in baretokens:
        if p in replacements:
            result += replacements[p]
        else:
            result += p
    elif p.strip() == "":
        pass
    else:
        raise ValueError("Malformed expression: '{0}'".format(p))
print(result)
# Do the computation using eval (should probably be safe, since
# maliscious code should be refused as malformed):
computed = int(eval(result))
print(computed)https://stackoverflow.com/questions/43043856
复制相似问题