Python: Converting string into decimal number

可紊 提交于 2019-12-17 23:17:29

问题


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?


回答1:


If you want the result as the nearest binary floating point number use float:

result = [float(x.strip(' "')) for x in A1]

If you want the result stored exactly use Decimal instead of float:

from decimal import Decimal
result = [Decimal(x.strip(' "')) for x in A1]



回答2:


You will need to use strip() because of the extra bits in the strings.

A2 = [float(x.strip('"')) for x in A1]



回答3:


use the built in float() function in a list comprehension.

A2 = [float(v.replace('"','').strip()) for v in A1]




回答4:


If you are converting price (in string) to decimal price then....

from decimal import Decimal

price = "14000,45"
price_in_decimal = Decimal(price.replace(',',''))



回答5:


A2 = [float(x.strip('"')) for x in A1] works, @Jake , but there are unnecessary 0s




回答6:


If you are converting string to float:

import re
A1 = [' "29.0" ',' "65.2" ',' "75.2" ']
float_values = [float(re.search(r'\d+.\d+',number).group()) for number in A1]
print(float_values)
>>> [29.0, 65.2, 75.2]


来源:https://stackoverflow.com/questions/4643991/python-converting-string-into-decimal-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!