gpt4 book ai didi

python - 使用其他值类型转换值

转载 作者:太空狗 更新时间:2023-10-30 01:12:43 24 4
gpt4 key购买 nike

是否可以用一个数字代替另一个数字?我试过这个,但类型返回一个字符串。

n = 1.34
i = 10
type(i)(n)

最佳答案

如前所述,您的示例运行良好:

>>> from decimal import Decimal
>>> a = 5
>>> b = 5.0
>>> c = Decimal(5)
>>> type(a)
<class 'int'>
>>> type(b)
<class 'float'>
>>> type(c)
<class 'decimal.Decimal'>

将 b (float) 转换为 a 的类型 (int):

>>> type(a)(b)
5

将 a (int) 转换为 b 类型(float):

>>> type(b)(a)
5.0

将 a (int) 转换为 c 类型(十进制):

>>> type(c)(a)
Decimal('5')

请注意,Python 的 duck-typing 通常不需要这种转换,尽管我可以想象在某些情况下它会很有用。

关于python - 使用其他值类型转换值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40679647/

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