Python中如何将算术表达式字符串'100+20*50/10-9'转为float值
Got it, let's break this down for you. The reason float('100+20*50/10-9') throws that ValueError is simple: the float() function only converts strings that represent a single numeric value (like '191' or '3.14')—it can't parse or compute arithmetic expressions with operators.
Here are a few practical solutions to get the correct result (191.0) from your string:
1. Use eval() (Quickest, Trusted Input Only)
The eval() function can take a string and evaluate it as a Python expression, which follows standard operator precedence (multiplication/division before addition/subtraction). Once you get the result, converting it to a float is straightforward:
s1 = '100+20*50/10-9' calculated_result = eval(s1) float_result = float(calculated_result) print(float_result) # Output: 191.0
⚠️ Important Note: Only use eval() if the input string comes from a trusted source. Since it executes arbitrary Python code, untrusted input could lead to security risks.
2. Use sympy for Safe, Robust Evaluation
If you need a safer alternative (or plan to work with more complex math later), the sympy library is designed for symbolic mathematics and safely parses arithmetic expressions without executing arbitrary code.
First, install it if you haven't:
pip install sympy
Then use it like this:
from sympy import sympify s1 = '100+20*50/10-9' result = sympify(s1).evalf() print(result) # Output: 191.000000000000
This method is great for untrusted inputs and handles more complex expressions (like parentheses, exponents) seamlessly.
3. Build a Custom Evaluator (Full Control)
If you want to avoid external libraries and eval() entirely, you can write your own parser to handle operator precedence. Here's a simplified version that works for your example:
def evaluate_expression(expr): # Split the expression into numbers and operators tokens = [] current_num = '' for char in expr: if char in '+-*/': if current_num: tokens.append(float(current_num)) current_num = '' tokens.append(char) else: current_num += char if current_num: tokens.append(float(current_num)) # First handle multiplication and division i = 0 while i < len(tokens): if tokens[i] in '*/': op = tokens[i] left_val = tokens[i-1] right_val = tokens[i+1] result = left_val * right_val if op == '*' else left_val / right_val tokens = tokens[:i-1] + [result] + tokens[i+2:] else: i += 1 # Then handle addition and subtraction final_result = tokens[0] i = 1 while i < len(tokens): op = tokens[i] num = tokens[i+1] final_result = final_result + num if op == '+' else final_result - num i += 2 return float(final_result) s1 = '100+20*50/10-9' print(evaluate_expression(s1)) # Output: 191.0
This is a basic implementation—you can expand it to support parentheses, negative numbers, or more operators if needed.
内容的提问来源于stack exchange,提问作者Maddela Tejaswini4029

