如何将Python计算表达式转换为可复制的目标字符串形式?
Got it, let's fix this so you get the exact string (10+20)*cos(u) instead of the numeric calculation result!
The issue with your original code is that you're evaluating the mathematical expression first (calculating (A+B)*cos(u) as a numeric value/array) and then printing that result. Instead, you need to construct the string representation of the expression without computing it.
Here's the straightforward solution using Python's f-strings (which make string formatting super clean):
A = 10 B = 20 # Build the expression string using f-string interpolation expression = f"({A}+{B})*cos(u)" print(expression)
Running this will output exactly what you need:
(10+20)*cos(u)
Bonus tip:
If you ever change the values of A or B later, this code will automatically update the expression string to match the new values. For example, if you set A=15 and B=25, it'll output (15+25)*cos(u) without you having to manually edit the string.
内容的提问来源于stack exchange,提问作者shoggananna

