Search code examples
pythonlistfinance

get the value without ' '


Hi what I want to do is this.

from googlefinance import getQuotes

def live_price(symbol):
    price = getQuotes(symbol)[0].values()[3]
    print price

If I run this, it will give me a price of a certain stock I entered in the func of live_price. But I want to do some calculation like this:

live_price('A')+live_price('B')

But since print does not give me the price as an "output" I cannot use those numbers for calculating something.

So I tried just price instead of print price at the last line. Then it gives me the price of a certain stock as an output so that I can use it for calculating. But the thing is that the number is a string, it will not calculate properly.

What should I do to pull the price as an output so that I can use the number to compute things that I want to calculate?


Solution

  • Sounds like you have a 'string'. You want a number, so convert it to a float or Decimal:

    In [1]: my_str = '1.35'
    
    In [2]: my_str_as_a_number = float(my_str)
    
    In [3]: my_str_as_a_number
    Out[3]: 1.35
    
    In [4]: my_str_as_a_number + 1
    Out[4]: 2.35
    

    float is built-in, but if you want Decimal you need to import it first.

    In [5]: from decimal import Decimal
    
    In [6]: my_str_as_a_decimal = Decimal(my_str)
    
    In [7]: my_str_as_a_decimal + 1
    Out[7]: Decimal('2.35')
    

    You can convert Decimal to float as well.

    In [8]: float(_)
    Out[8]: 2.35
    

    The advantage of using Decimals over using floating point is that Decimals avoid some common gotchas caused by floating point representation's inexact nature.