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?
Converting a string to a decimal value or decimal equivalent can be done using the Decimal. TryParse() method. It converts the string representation of a number to its decimal equivalent.
To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .
In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer. But use of the int() function is not the only way to do so.
If you are converting price (in string) to decimal price then.... from decimal import Decimal price = "14000,45" price_in_decimal = Decimal(price. replace(',','. '))
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With