Python - Convert intergers to floats within a string
<p>I have an equation in the form of a string, something like this:</p>

<pre><code>(20 + 3) / 4
</code></pre>

<p>I can easily solve this equation by using <code>eval()</code>, but it will give me an answer of <code>5</code>, not the correct answer of <code>5.75</code>.  I know this is because <code>20</code>, <code>3</code>, and <code>4</code> are integers.  So I was wondering, is there any way to just tack a <code>.0</code> onto the end of them?  Or is there some other trick I should use to make <code>eval()</code> think they are floats?<br>
<strong>Note:</strong> the numbers will not always be integers, so it would be great if the solution could detect if they are integers and treat them accordingly.</p>

<p><strong>Note #2:</strong> I'm using python 2.7</p>

<p><strong>Note #3:</strong> I already know that "Python 2 is legacy, Python 3 is the future."</p>

<p>Thanks!</p>

<p>You could use <a href="http://docs.sympy.org/dev/index.html" rel="nofollow"><code>sympy</code></a> to parse the string using <a href="http://docs.sympy.org/dev/modules/parsing.html" rel="nofollow"><code>sympy_parser.parse_expr</code></a> and then solve/simplify it:</p>

<pre><code>&gt;&gt;&gt; from sympy.parsing import sympy_parser
&gt;&gt;&gt; exp = '(20 + 3) / 4'
&gt;&gt;&gt; sympy_parser.parse_expr(exp).round(2)
5.75
</code></pre>

<p>This would also work for other valid mathematical expressions.</p>

python string python-2.7