Python:将字符串转换为十进制数 [英] Python: Converting string into decimal number
本文介绍了Python:将字符串转换为十进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个使用以下格式的字符串的python列表:
I have a python list with strings in this format:
A1 = [' "29.0" ',' "65.2" ',' "75.2" ']
如何将这些字符串转换为十进制数字以执行算术运算
How do I convert those strings into decimal numbers to perform arithmetic operations on the list elements?
推荐答案
如果希望将结果作为最接近的二进制浮点数,请使用浮动
:
If you want the result as the nearest binary floating point number use float
:
result = [float(x.strip(' "')) for x in A1]
如果要完全存储结果,请使用 十进制
,而不是 float
:
If you want the result stored exactly use Decimal
instead of float
:
from decimal import Decimal
result = [Decimal(x.strip(' "')) for x in A1]
这篇关于Python:将字符串转换为十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文