擅长:python、mysql、java
<p>最简单的方法是使用<code>float()</code>将字符串转换为浮点:</p>
<pre><code>>>> float('42.666')
42.666
</code></pre>
<p>如果无法将其转换为浮点,则会得到一个<code>ValueError</code>:</p>
<pre><code>>>> float('Not a float')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'Not a float'
</code></pre>
<p>使用<code>try</code>/<code>except</code>块通常被认为是处理此问题的最佳方法:</p>
<pre><code>try:
width = float(width)
except ValueError:
print('Width is not a number')
</code></pre>
<p>注意,您还可以对<code>float()</code>使用<code>is_integer()</code>来检查它是否是整数:</p>
<pre><code>>>> float('42.666').is_integer()
False
>>> float('42').is_integer()
True
</code></pre>