Search code examples
pythonstringformat

Understanting what the syntax for {:.2} means in python


I am working on creating a linear regression model for a specific data set, I am following an example I found on you tube, at some point I calculate the kurtosis and the skewness as below:

# calculate the excess kurtosis using the fisher method. The alternative is Pearson which 
calculates regular kurtosis.
exxon_kurtosis = kurtosis(price_data['exxon_price'], fisher = True)
oil_kurtosis = kurtosis(price_data['oil_price'], fisher = True)

# calculate the skewness
exxon_skew = skew(price_data['exxon_price'])
oil_skew = skew(price_data['oil_price'])

display("Exxon Excess Kurtosis: {:.2}".format(exxon_kurtosis))  # this looks fine
display("Oil Excess Kurtosis: {:.2}".format(oil_kurtosis))      # this looks fine

display("Exxon Skew: {:.2}".format(exxon_skew))          # moderately skewed
display("Oil Skew: {:.2}".format(oil_skew))              # moderately skewed, it's a 
little high but we will accept it.

I am new to python, and the following code confuses me here {:.2}, please can someone explain what this part {:.2}

display("Exxon Excess Kurtosis: {:.2}".format(exxon_kurtosis))

Solution

  • The kurtosis and skew functions are doing the calculation, while the display function is probably just some form of print() for that environment!

    ".. {:.2}".format(x) is a string formatter which rounds floating points to 2 significant digits

    >>> "{:.2}".format(3.0)
    '3.0'
    >>> "{:.2}".format(0.1555)
    '0.16'
    >>> "{:.2}".format(3.1555)
    '3.2'
    

    String formatting is exhaustively detailed here