擅长:python、mysql、java
<p>您必须使用两种不同格式的字符串和<code>round</code>来检测何时使用它们:</p>
<pre><code>for i in [1002, 1009]:
print(f'{i/1000:.0f}') if round(i/1000, 2) == 1.00 else print(f'{i/1000:.2f}')
</code></pre>
<p>这将产生:</p>
<pre><code>1
1.01
</code></pre>
<p>请参阅<a href="https://docs.python.org/3/library/string.html#format-specification-mini-language" rel="nofollow noreferrer">Format Specification Mini-Language</a></p>
<blockquote>
<p>The precision is a decimal number indicating how many digits should be displayed after the decimal point for a floating point value formatted with <code>'f'</code> and <code>'F'</code>, or before and after the decimal point for a floating point value formatted with <code>'g'</code> or <code>'G'</code>.</p>
</blockquote>
<p>取决于你的品味,是使用我建议的<code>round</code>方法还是你提到的<code>strip</code>方法。如果您以代码应该清晰、简洁和可维护的方式理解Pythonic,那么我将使用<code>round</code>方法处理两种格式的字符串,因为这对于未来的开发人员来说是非常可读/可理解的</p>