gpt4 book ai didi

python - 尝试设置小数位数时语法无效

转载 作者:太空宇宙 更新时间:2023-11-04 10:45:43 26 4
gpt4 key购买 nike

我正在使用 Python 3.3.2,我试图在算术运算后设置小数位数,但它一直向我抛出 SyntaxError: invalid syntax。我似乎无法弄清楚我哪里出错了。谢谢!

exampleInt = 123.456789
print({:.2f}.format(exampleInt)

我一直在 Python shell 中收到冒号处的错误。

最佳答案

:.2f 不是有效文字。您需要一个格式字符串,并且字符串文字需要引号:

In [1]: exampleInt = 123.456789

In [2]: print('{:.2f}'.format(exampleInt))
123.46

此外,Delgan 是对的,您的示例中缺少右括号,但在这种情况下,Python shell 将继续该行,而不是引发 SyntaxError

关于python - 尝试设置小数位数时语法无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17501296/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com