Python中eval(string)函数

Python中eval(string)函数,是字符串的专属函数,用于提取字符串中表达式的值,可以用于将字符串转为其他数据类型,还可以用于表达式求值.常用于文件数据的加载.

# 1,将字符串转为整型
a = "123"
print(type(eval(a)))
# 2,将字符串转为浮点型
b = "1.23"
print(type(eval(b)))
# 3,将字符串转为列表
c = "[1, 2, 3]"
print(type(eval(c)))
# 4,将字符串转为元组
d = "(1,2,3,4)"
print(type(eval(d)))
# 5,将字符串转为字典
e = "{'a':1}"
print(type(eval(e)))
# 6,将字符串转为集合
g = "{1, 2, 3}"
print(type(eval(g)))
# 7,表达式求值
h = "1 + 2"
i = "100 * 10"
print(eval(h))
print(eval(i))
<class 'int'>
<class 'float'>
<class 'list'>
<class 'tuple'>
<class 'dict'>
<class 'set'>
3
1000

### C++ Equivalent Function of Python’s `eval` In Python, the `eval` function parses and evaluates a string as a valid Python expression. In contrast, C++ does not have a direct built-in equivalent to Python's `eval`. However, similar functionality can be achieved using third-party libraries or by implementing custom parsing logic. One common approach involves utilizing external libraries such as muParserX or ExprTk which provide robust mathematical expression evaluation capabilities: #### Using ExprTk Library ExprTk is one of the most efficient run-time mathematical expression parsers and evaluators available for C++. Below demonstrates how this library could serve similarly to Python's `eval`. ```cpp #include <iostream> #include <exprtk.hpp> int main() { std::string expression = "2 + 3 * sin(pi / 4)"; typedef exprtk::expression<double> expression_t; typedef exprtk::parser<double> parser_t; expression_t expression_obj; parser_t parser; if (parser.compile(expression, expression_obj)) { double result = expression_obj.value(); std::cout << "Result: " << result << std::endl; // Output should match python eval output. } else { std::cout << "Compilation failed." << std::endl; } return 0; } ``` For simple arithmetic operations without requiring complex expressions, another alternative would involve manually constructing and executing code through compiler APIs like Clang/LLVM but this introduces significant complexity and security risks comparable to those associated with misuse of Python's `eval`[^1].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值