F-string不会将浮点数格式化为整数。

huangapple go评论67阅读模式
英文:

F-string not formatting floats into an integer

问题

通常,我使用字符串格式化。但是,正如我发现的,f-string是新的字符串格式化方式,而且速度更快,我想使用它。<br/>但是,当我尝试使用f-string将浮点数格式化为整数时,我遇到了问题。以下是我尝试过的内容:<br/>使用字符串格式化

'%5d'%1223      # 得到 --&gt; ' 1223'
'%5d'%1223.555  # 得到 --&gt; ' 1223'

使用f-string格式化

f'{1223:5d}'     # 得到 --&gt; ' 1223' ==&gt; 正确
f'{1223.555:5d}' # 报错
# 错误信息为“ValueError: Unknown format code 'd' for object of type 'float'”

我是否漏掉了什么?

英文:

Usually, I use % string formatting. But, as I discovered f-string is the new way of string formatting and it is faster as well, I want to use it. <br/>
But, I am facing a problem when formatting a float into an integer using f-string. Following is what I have tried:<br/>
Using % string formatting

&#39;%5d&#39;%1223      # yields --&gt; &#39; 1223&#39;
&#39;%5d&#39;%1223.555  # yields --&gt; &#39; 1223&#39;

Using f-string formatting

f&#39;{1223:5d}&#39;     # yields --&gt; &#39; 1223&#39; ==&gt; correct
f&#39;{1223.555:5d}&#39; # gives error
# error is &quot;ValueError: Unknown format code &#39;d&#39; for object of type &#39;float&#39;&quot;

Am I missing something?

答案1

得分: 2

错误的原因是格式说明符 d 专门用于格式化整数,而不是浮点数。您可以改用通用格式说明符 f

f'{int(1223.555):5f}'
英文:

The reason for this error is that the format specifier d is specifically for formatting integers, not floats.You can use the general format specifier f instead.

f&#39;{int(1223.555):5d}&#39;

huangapple
  • 本文由 发表于 2023年7月13日 16:46:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76677507.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定