Python:将字符串转换为十进制数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4643991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:43:53  来源:igfitidea点击:

Python: Converting string into decimal number

pythonstringfloating-pointdecimal

提问by Sankar A

I have a python list with strings in this format:

我有一个带有以下格式字符串的 python 列表:

A1 = [' "29.0" ',' "65.2" ',' "75.2" ']

How do I convert those strings into decimal numbers to perform arithmetic operations on the list elements?

如何将这些字符串转换为十进制数以对列表元素执行算术运算?

回答by Mark Byers

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

如果您希望结果为最接近的二进制浮点数,请使用float

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

If you want the result stored exactly use Decimalinstead of float:

如果您希望准确存储结果,请使用Decimal而不是float

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

回答by Jake

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

strip()由于字符串中的额外位,您将需要使用。

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

回答by farzad

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

在列表理解中使用内置的 float() 函数。

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

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

回答by tekknolagi

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

A2 = [float(x.strip('"')) for x in A1]作品,@Jake,但有不必要的 0

回答by Nids Barthwal

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

如果您将价格(以字符串形式)转换为十进制价格,那么....

from decimal import Decimal

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

No need for the replace if your strings already use dots as a decimal separator

如果您的字符串已经使用点作为小数点分隔符,则无需替换

回答by Pradam

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]