简体   繁体   中英

How can I turn a string that contains numbers and operators into a result?

I want to convert this string into a result n for the output to be 11.

a = "1+5*6/3"
print (a) 

The eval() built-in function can evaluate a Python expression including any arithmetic expression. But note the eval() function is a security concern because it can evaluate any arbitrary Python expression or statement so should be used only if the input to evaluate is controlled and trusted user input . There are examples to why eval() is dangerous in this question .

a = "1+5*6/3"
result = eval(a)
print(result)

Output:

11.0

Using ast module as an alternative to eval()

A safe alternative to eval() is using ast.literal_eval . Recent Python 3 versions disallows passing simple strings to ast.literal_eval() as an argument. Now must parse the string to buld an Abstract Syntax Tree (AST) then evaluate it against a grammar. This related answer provides an example to evaluate simple arithmetic expressions safely.

You can directly use the python eval function.

a = eval("1+5*6/3")
print(a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM